familia 2.0.0.pre10 → 2.0.0.pre12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +75 -12
  3. data/CLAUDE.md +4 -54
  4. data/Gemfile.lock +1 -1
  5. data/changelog.d/README.md +45 -34
  6. data/docs/archive/FAMILIA_RELATIONSHIPS.md +1 -1
  7. data/docs/archive/FAMILIA_UPDATE.md +1 -1
  8. data/docs/archive/README.md +15 -19
  9. data/docs/guides/Home.md +1 -1
  10. data/docs/guides/Implementation-Guide.md +1 -1
  11. data/docs/guides/relationships-methods.md +1 -1
  12. data/docs/migrating/.gitignore +2 -0
  13. data/docs/migrating/v2.0.0-pre.md +84 -0
  14. data/docs/migrating/v2.0.0-pre11.md +255 -0
  15. data/docs/migrating/v2.0.0-pre12.md +306 -0
  16. data/docs/migrating/v2.0.0-pre5.md +110 -0
  17. data/docs/migrating/v2.0.0-pre6.md +154 -0
  18. data/docs/migrating/v2.0.0-pre7.md +222 -0
  19. data/docs/overview.md +6 -7
  20. data/{examples/redis_command_validation_example.rb → docs/reference/auditing_database_commands.rb} +29 -32
  21. data/examples/{bit_encoding_integration.rb → permissions.rb} +30 -27
  22. data/examples/{relationships_basic.rb → relationships.rb} +2 -3
  23. data/examples/safe_dump.rb +281 -0
  24. data/familia.gemspec +4 -4
  25. data/lib/familia/base.rb +52 -0
  26. data/lib/familia/{encryption_request_cache.rb → encryption/request_cache.rb} +1 -1
  27. data/lib/familia/errors.rb +2 -0
  28. data/lib/familia/features/autoloader.rb +57 -0
  29. data/lib/familia/features/external_identifier.rb +310 -0
  30. data/lib/familia/features/object_identifier.rb +307 -0
  31. data/lib/familia/features/safe_dump.rb +66 -72
  32. data/lib/familia/features.rb +93 -5
  33. data/lib/familia/horreum/subclass/definition.rb +47 -3
  34. data/lib/familia/secure_identifier.rb +51 -75
  35. data/lib/familia/verifiable_identifier.rb +162 -0
  36. data/lib/familia/version.rb +1 -1
  37. data/lib/familia.rb +1 -0
  38. data/setup.cfg +1 -8
  39. data/try/core/secure_identifier_try.rb +47 -18
  40. data/try/core/verifiable_identifier_try.rb +171 -0
  41. data/try/features/{external_identifiers/external_identifiers_try.rb → external_identifier/external_identifier_try.rb} +25 -28
  42. data/try/features/feature_improvements_try.rb +126 -0
  43. data/try/features/{object_identifiers/object_identifiers_integration_try.rb → object_identifier/object_identifier_integration_try.rb} +28 -30
  44. data/try/features/{object_identifiers/object_identifiers_try.rb → object_identifier/object_identifier_try.rb} +13 -13
  45. data/try/features/real_feature_integration_try.rb +7 -6
  46. data/try/features/safe_dump/safe_dump_try.rb +8 -9
  47. data/try/helpers/test_helpers.rb +17 -17
  48. metadata +30 -22
  49. data/changelog.d/fragments/.keep +0 -0
  50. data/changelog.d/template.md.j2 +0 -29
  51. data/lib/familia/features/external_identifiers/external_identifier_field_type.rb +0 -120
  52. data/lib/familia/features/external_identifiers.rb +0 -111
  53. data/lib/familia/features/object_identifiers/object_identifier_field_type.rb +0 -91
  54. data/lib/familia/features/object_identifiers.rb +0 -194
@@ -0,0 +1,255 @@
1
+ # Migrating Guide: v2.0.0-pre11
2
+
3
+ This version introduces significant improvements to Familia's feature system, making it easier to organize and use features across complex projects.
4
+
5
+ ## Enhanced Feature System
6
+
7
+ ### Model-Specific Feature Registration
8
+
9
+ Previously, all features were registered globally. Now you can register features specific to individual model classes, allowing for better organization and namespace management.
10
+
11
+ #### Before
12
+ ```ruby
13
+ # Global feature registration only
14
+ module MyProjectFeature
15
+ # Feature implementation
16
+ end
17
+ Familia::Base.add_feature MyProjectFeature, :my_project_feature
18
+
19
+ class Customer < Familia::Horreum
20
+ feature :my_project_feature
21
+ end
22
+
23
+ class Session < Familia::Horreum
24
+ feature :my_project_feature # Same global feature
25
+ end
26
+ ```
27
+
28
+ #### After
29
+ ```ruby
30
+ # Model-specific feature registration
31
+ module CustomerSpecificFeature
32
+ # Feature implementation
33
+ end
34
+
35
+ # Register feature only for Customer and its subclasses
36
+ Customer.add_feature CustomerSpecificFeature, :customer_specific
37
+
38
+ class Customer < Familia::Horreum
39
+ feature :customer_specific # Available via Customer's registry
40
+ end
41
+
42
+ class PremiumCustomer < Customer
43
+ feature :customer_specific # Inherited via ancestry chain
44
+ end
45
+
46
+ class Session < Familia::Horreum
47
+ # feature :customer_specific # Not available - would raise error
48
+ end
49
+ ```
50
+
51
+ **Benefits:**
52
+ - Features can have the same name across different model hierarchies
53
+ - Standardized naming: `deprecated_fields.rb` instead of `customer_deprecated_fields.rb`
54
+ - Natural inheritance through Ruby's class hierarchy
55
+
56
+ ## SafeDump DSL Improvements
57
+
58
+ The new DSL replaces the brittle `@safe_dump_fields` class instance variable pattern with clean, explicit methods.
59
+
60
+ ### Before
61
+ ```ruby
62
+ class Customer < Familia::Horreum
63
+ feature :safe_dump
64
+
65
+ # Brittle - hard to move to feature modules, confusing syntax
66
+ @safe_dump_fields = [
67
+ :custid,
68
+ :email,
69
+ { active: ->(obj) { obj.active? } },
70
+ { display_name: ->(obj) { "#{obj.name} (#{obj.custid})" } }
71
+ ]
72
+ end
73
+ ```
74
+
75
+ ### After
76
+ ```ruby
77
+ class Customer < Familia::Horreum
78
+ feature :safe_dump
79
+
80
+ # Clean DSL - easy to understand and organize
81
+ safe_dump_field :custid
82
+ safe_dump_field :email
83
+ safe_dump_field :active, ->(obj) { obj.active? }
84
+ safe_dump_field :display_name, ->(obj) { "#{obj.name} (#{obj.custid})" }
85
+
86
+ # Or define multiple fields at once
87
+ safe_dump_fields :created, :updated, { status: ->(obj) { obj.role } }
88
+ end
89
+ ```
90
+
91
+ **New methods available:**
92
+ - `safe_dump_field(name, callable = nil)` - Define a single field
93
+ - `safe_dump_fields(*fields)` - Define multiple fields or get field names
94
+ - `safe_dump_field_names` - Get array of field names
95
+ - `safe_dump_field_map` - Get the internal callable map
96
+
97
+ **Backward Compatibility:**
98
+ - `set_safe_dump_fields(*fields)` - Legacy setter method (still works)
99
+ - The old `@safe_dump_fields` pattern is no longer supported
100
+
101
+ ## Auto-loading Features
102
+
103
+ ### Before: Manual Loading
104
+ ```ruby
105
+ # apps/api/v2/models/customer/features.rb
106
+
107
+ # Manual feature loading (copied from Familia)
108
+ features_dir = File.join(__dir__, 'features')
109
+ if Dir.exist?(features_dir)
110
+ Dir.glob(File.join(features_dir, '*.rb')).each do |feature_file|
111
+ require_relative feature_file
112
+ end
113
+ end
114
+
115
+ module V2
116
+ class Customer < Familia::Horreum
117
+ # Features now available for use
118
+ feature :deprecated_fields
119
+ end
120
+ end
121
+ ```
122
+
123
+ ### After: Automatic Loading
124
+ ```ruby
125
+ # apps/api/v2/models/customer/features.rb
126
+ module V2::Customer
127
+ module Features
128
+ include Familia::Features::Autoloader
129
+ # Automatically discovers and loads all *.rb files from customer/features/
130
+ end
131
+ end
132
+
133
+ module V2
134
+ class Customer < Familia::Horreum
135
+ # Features automatically loaded and available
136
+ feature :deprecated_fields
137
+ end
138
+ end
139
+ ```
140
+
141
+ **Directory structure this enables:**
142
+ ```
143
+ models/
144
+ ├── customer/
145
+ │ ├── features/
146
+ │ │ ├── deprecated_fields.rb # Standardized names!
147
+ │ │ ├── legacy_support.rb
148
+ │ │ └── stripe_integration.rb
149
+ │ └── features.rb # Include Autoloader here
150
+ ├── session/
151
+ │ ├── features/
152
+ │ │ ├── deprecated_fields.rb # Same name, different implementation
153
+ │ │ └── expiration_hooks.rb
154
+ │ └── features.rb
155
+ └── customer.rb
156
+ ```
157
+
158
+ ## Field Definitions in Feature Modules
159
+
160
+ Feature modules can now define fields directly in their `ClassMethods` modules. When a class extends the module, the field definitions execute in the extending class's context.
161
+
162
+ ### Example
163
+ ```ruby
164
+ # features/common_fields.rb
165
+ module CommonFields
166
+ def self.included(base)
167
+ base.extend ClassMethods
168
+ end
169
+
170
+ module ClassMethods
171
+ # These field calls execute in the extending class's context
172
+ field :created
173
+ field :updated
174
+ field :version
175
+
176
+ def touch_updated
177
+ self.updated = Time.now.to_i
178
+ end
179
+ end
180
+
181
+ Familia::Base.add_feature self, :common_fields
182
+ end
183
+
184
+ # Usage
185
+ class Customer < Familia::Horreum
186
+ feature :common_fields
187
+ # Now has :created, :updated, :version fields and touch_updated class method
188
+ end
189
+ ```
190
+
191
+ ## Migration Steps
192
+
193
+ ### 1. Update SafeDump Usage
194
+ Replace all `@safe_dump_fields` definitions with the new DSL:
195
+
196
+ ```ruby
197
+ # Find and replace pattern:
198
+ # Old: @safe_dump_fields = [:field1, :field2, { field3: ->(obj) { ... } }]
199
+ # New: safe_dump_fields :field1, :field2, { field3: ->(obj) { ... } }
200
+
201
+ # Or use individual field definitions for better readability:
202
+ safe_dump_field :field1
203
+ safe_dump_field :field2
204
+ safe_dump_field :field3, ->(obj) { ... }
205
+ ```
206
+
207
+ ### 2. Set Up Auto-loading (Optional)
208
+ If you have project-specific features, set up auto-loading:
209
+
210
+ ```ruby
211
+ # Create: models/[model_name]/features.rb
212
+ module YourProject
213
+ module ModelName
214
+ module Features
215
+ include Familia::Features::Autoloader
216
+ end
217
+ end
218
+ end
219
+
220
+ # Require this file before your model definitions
221
+ require_relative 'model_name/features'
222
+ ```
223
+
224
+ ### 3. Organize Features by Model (Optional)
225
+ Consider reorganizing shared feature names by model:
226
+
227
+ ```ruby
228
+ # Before: features/customer_deprecated_fields.rb
229
+ # After: models/customer/features/deprecated_fields.rb
230
+
231
+ # This allows multiple models to have their own deprecated_fields.rb
232
+ ```
233
+
234
+ ### 4. Test Your Changes
235
+ Run your test suite to ensure all SafeDump functionality works correctly:
236
+
237
+ ```ruby
238
+ # Verify SafeDump DSL works
239
+ model = YourModel.new(field1: 'value')
240
+ result = model.safe_dump
241
+ puts result.keys # Should include your defined fields
242
+ ```
243
+
244
+ ## Breaking Changes
245
+
246
+ 1. **`@safe_dump_fields` no longer supported** - Must migrate to DSL methods
247
+ 2. **SafeDump field order** - Fields are now returned in definition order via Hash keys (Ruby 1.9+ behavior)
248
+
249
+ ## New Capabilities Unlocked
250
+
251
+ 1. **Standardized feature names** across different models
252
+ 2. **Cleaner SafeDump definitions** that can be easily moved to feature modules
253
+ 3. **Automatic feature discovery** for better project organization
254
+ 4. **Model-specific feature registries** for better namespace management
255
+ 5. **Field definitions in feature modules** for shared functionality
@@ -0,0 +1,306 @@
1
+ # Migrating Guide: v2.0.0-pre12
2
+
3
+ This version introduces significant security improvements to Familia's identifier system, including verifiable identifiers with HMAC signatures, scoped identifier namespaces, and hardened external identifier derivation to prevent potential security vulnerabilities.
4
+
5
+ ## VerifiableIdentifier Feature
6
+
7
+ ### Overview
8
+
9
+ The new `Familia::VerifiableIdentifier` module allows applications to create and verify identifiers with embedded HMAC signatures. This enables stateless confirmation that an identifier was generated by your application, preventing forged IDs from malicious sources.
10
+
11
+ ### Basic Usage
12
+
13
+ ```ruby
14
+ class Customer < Familia::Horreum
15
+ feature :verifiable_identifier
16
+
17
+ # Required: Set the HMAC secret (do this once in your app initialization)
18
+ # Generate with: SecureRandom.hex(64)
19
+ ENV['VERIFIABLE_ID_HMAC_SECRET'] = 'your_64_character_hex_secret'
20
+ end
21
+
22
+ # Generate a verifiable identifier
23
+ customer = Customer.new
24
+ verifiable_id = customer.generate_verifiable_id
25
+ # => "cust_1234567890abcdef_a1b2c3d4e5f6789..."
26
+
27
+ # Verify the identifier later (stateless verification)
28
+ if Customer.verified_identifier?(verifiable_id)
29
+ # Identifier is valid and was generated by this application
30
+ original_id = Customer.extract_identifier(verifiable_id)
31
+ customer = Customer.new(original_id)
32
+ else
33
+ # Identifier is forged or corrupted
34
+ raise SecurityError, "Invalid identifier"
35
+ end
36
+ ```
37
+
38
+ ### Scoped VerifiableIdentifier
39
+
40
+ The new `scope` parameter enables cryptographically isolated identifier namespaces for multi-tenant, multi-domain, or multi-environment applications.
41
+
42
+ #### Before (Global Scope)
43
+ ```ruby
44
+ # All identifiers share the same cryptographic space
45
+ admin_id = admin.generate_verifiable_id
46
+ user_id = user.generate_verifiable_id
47
+
48
+ # Risk: Cross-contamination between different contexts
49
+ ```
50
+
51
+ #### After (Scoped Namespaces)
52
+ ```ruby
53
+ # Production environment
54
+ prod_customer_id = customer.generate_verifiable_id(scope: 'production')
55
+ prod_admin_id = admin.generate_verifiable_id(scope: 'production:admin')
56
+
57
+ # Development environment
58
+ dev_customer_id = customer.generate_verifiable_id(scope: 'development')
59
+
60
+ # Multi-tenant application
61
+ tenant_a_id = user.generate_verifiable_id(scope: "tenant:#{tenant_a.id}")
62
+ tenant_b_id = user.generate_verifiable_id(scope: "tenant:#{tenant_b.id}")
63
+
64
+ # Verification requires matching scope
65
+ Customer.verified_identifier?(prod_customer_id, scope: 'production') # => true
66
+ Customer.verified_identifier?(prod_customer_id, scope: 'development') # => false
67
+ ```
68
+
69
+ **Scope Benefits:**
70
+ - **Multi-tenant isolation**: Tenant A cannot forge identifiers for Tenant B
71
+ - **Environment separation**: Production IDs cannot be used in development
72
+ - **Role-based security**: Admin scopes separate from user scopes
73
+ - **Full backward compatibility**: Existing code without scopes continues to work
74
+
75
+ ### Key Management
76
+
77
+ #### Secure Secret Generation
78
+ ```ruby
79
+ # Generate a cryptographically secure HMAC secret
80
+ require 'securerandom'
81
+ secret = SecureRandom.hex(64) # 512-bit secret
82
+ puts "VERIFIABLE_ID_HMAC_SECRET=#{secret}"
83
+ ```
84
+
85
+ #### Environment Configuration
86
+ ```ruby
87
+ # config/application.rb or equivalent
88
+ # Set this BEFORE any VerifiableIdentifier usage
89
+ ENV['VERIFIABLE_ID_HMAC_SECRET'] = Rails.application.credentials.verifiable_id_secret
90
+
91
+ # Or configure programmatically
92
+ Familia::VerifiableIdentifier.hmac_secret = your_secret_string
93
+ ```
94
+
95
+ ## ObjectIdentifier Feature Improvements
96
+
97
+ ### Method Renaming
98
+
99
+ Method names have been updated for clarity and consistency:
100
+
101
+ #### Before
102
+ ```ruby
103
+ customer = Customer.new
104
+ objid = customer.generate_objid # Unclear what this generates
105
+ extid = Customer.generate_extid(objid) # Less secure class method
106
+ ```
107
+
108
+ #### After
109
+ ```ruby
110
+ customer = Customer.new
111
+ objid = customer.generate_object_identifier # Clear: generates object ID
112
+ extid = customer.derive_external_identifier # Clear: derives from objid, instance method
113
+ ```
114
+
115
+ **Migration:**
116
+ - Replace `generate_objid` → `generate_object_identifier`
117
+ - Replace `generate_external_identifier` → `derive_external_identifier`
118
+ - Remove usage of `generate_extid` (deprecated for security reasons)
119
+
120
+ ### Provenance Tracking
121
+
122
+ ObjectIdentifier now tracks which generator was used for each identifier:
123
+
124
+ ```ruby
125
+ class Customer < Familia::Horreum
126
+ feature :object_identifier
127
+
128
+ # Configure generator type
129
+ object_identifier_generator :uuid_v7 # or :uuid_v4, :hex, custom proc
130
+ end
131
+
132
+ customer = Customer.new
133
+ objid = customer.generate_object_identifier
134
+
135
+ # Provenance information available
136
+ puts customer.object_identifier_generator_type # => :uuid_v7
137
+ puts customer.objid_format # => :uuid (normalized format)
138
+ ```
139
+
140
+ **Benefits:**
141
+ - **Security auditing**: Know which generator created each identifier
142
+ - **Format normalization**: Eliminates ambiguity between UUID and hex formats
143
+ - **Migration support**: Track mixed generator usage during transitions
144
+
145
+ ## ExternalIdentifier Security Hardening
146
+
147
+ ### Provenance Validation
148
+
149
+ ExternalIdentifier now validates that objid values come from the ObjectIdentifier feature before deriving external identifiers.
150
+
151
+ #### Before (Potential Security Risk)
152
+ ```ruby
153
+ # Could derive external IDs from any string, including malicious input
154
+ extid = customer.derive_external_identifier("malicious_input")
155
+ ```
156
+
157
+ #### After (Hardened)
158
+ ```ruby
159
+ customer = Customer.new
160
+ customer.generate_object_identifier # Must generate objid first
161
+
162
+ # Only works with validated objid from ObjectIdentifier feature
163
+ extid = customer.derive_external_identifier # Secure: uses validated objid
164
+ ```
165
+
166
+ ### Improved Security Model
167
+
168
+ External identifiers are now derived using the internal objid as a seed for a new random value, rather than directly deriving from objid.
169
+
170
+ #### Before
171
+ ```ruby
172
+ # Direct derivation could leak information about objid
173
+ extid = hash(objid) # Information leakage risk
174
+ ```
175
+
176
+ #### After
177
+ ```ruby
178
+ # objid used as seed for new random value
179
+ extid = secure_hash(objid + additional_entropy) # No information leakage
180
+ ```
181
+
182
+ ### Error Handling Improvements
183
+
184
+ External identifier now raises clear errors for invalid usage:
185
+
186
+ ```ruby
187
+ class Customer < Familia::Horreum
188
+ feature :external_identifier # Missing: object_identifier dependency
189
+ end
190
+
191
+ customer = Customer.new
192
+ # Raises ExternalIdentifierError instead of returning nil
193
+ customer.derive_external_identifier
194
+ # => Familia::ExternalIdentifierError: Model does not have an objid field
195
+ ```
196
+
197
+ ## Migration Steps
198
+
199
+ ### 1. Update Method Names
200
+
201
+ Replace deprecated method names in your codebase:
202
+
203
+ ```bash
204
+ # Search and replace patterns:
205
+ grep -r "generate_objid" --include="*.rb" .
206
+ # Replace with: generate_object_identifier
207
+
208
+ grep -r "generate_external_identifier" --include="*.rb" .
209
+ # Replace with: derive_external_identifier
210
+
211
+ grep -r "generate_extid" --include="*.rb" .
212
+ # Remove usage - use derive_external_identifier instead
213
+ ```
214
+
215
+ ### 2. Add HMAC Secret for VerifiableIdentifier
216
+
217
+ If you plan to use VerifiableIdentifier:
218
+
219
+ ```ruby
220
+ # Generate secret
221
+ require 'securerandom'
222
+ secret = SecureRandom.hex(64)
223
+
224
+ # Add to your environment configuration
225
+ # .env, Rails credentials, or similar
226
+ VERIFIABLE_ID_HMAC_SECRET=your_generated_secret
227
+
228
+ # Verify configuration
229
+ puts ENV['VERIFIABLE_ID_HMAC_SECRET']&.length # Should be 128 characters
230
+ ```
231
+
232
+ ### 3. Update ExternalIdentifier Usage
233
+
234
+ Ensure proper dependency chain:
235
+
236
+ ```ruby
237
+ class YourModel < Familia::Horreum
238
+ # Required: ObjectIdentifier must come before ExternalIdentifier
239
+ feature :object_identifier
240
+ feature :external_identifier
241
+
242
+ # Configure generator if needed
243
+ object_identifier_generator :uuid_v7
244
+ end
245
+
246
+ # Usage pattern
247
+ model = YourModel.new
248
+ model.generate_object_identifier # Generate objid first
249
+ extid = model.derive_external_identifier # Then derive external ID
250
+ ```
251
+
252
+ ### 4. Review Security-Sensitive Code
253
+
254
+ Audit any code that processes identifiers from external sources:
255
+
256
+ ```ruby
257
+ # Before: Potentially unsafe
258
+ def process_identifier(external_id)
259
+ # Could process forged identifiers
260
+ model = Model.find_by_external_id(external_id)
261
+ end
262
+
263
+ # After: With verification
264
+ def process_identifier(verifiable_id)
265
+ # Verify identifier authenticity first
266
+ unless Model.verified_identifier?(verifiable_id)
267
+ raise SecurityError, "Invalid identifier"
268
+ end
269
+
270
+ original_id = Model.extract_identifier(verifiable_id)
271
+ model = Model.new(original_id)
272
+ end
273
+ ```
274
+
275
+ ## Breaking Changes
276
+
277
+ 1. **`generate_extid` removed** - Use instance-level `derive_external_identifier` instead
278
+ 2. **ExternalIdentifier validation** - Now raises `ExternalIdentifierError` instead of returning `nil` for models without objid
279
+ 3. **Method names changed** - `generate_objid` → `generate_object_identifier`, `generate_external_identifier` → `derive_external_identifier`
280
+
281
+ ## New Security Capabilities
282
+
283
+ 1. **Cryptographic identifier verification** - Prevent forged IDs with HMAC signatures
284
+ 2. **Scoped namespaces** - Isolate identifiers by tenant, environment, or role
285
+ 3. **Provenance tracking** - Know which generator created each identifier
286
+ 4. **Information leakage prevention** - External IDs no longer directly expose internal IDs
287
+ 5. **Input validation** - Clear error messages for invalid operations
288
+
289
+ ## Testing Your Migration
290
+
291
+ ```ruby
292
+ # Test ObjectIdentifier changes
293
+ model = YourModel.new
294
+ objid = model.generate_object_identifier
295
+ extid = model.derive_external_identifier
296
+ puts "Generator: #{model.object_identifier_generator_type}"
297
+
298
+ # Test VerifiableIdentifier (if using)
299
+ vid = model.generate_verifiable_id
300
+ puts "Verifiable: #{YourModel.verified_identifier?(vid)}"
301
+
302
+ # Test scoped identifiers (if using)
303
+ scoped_vid = model.generate_verifiable_id(scope: 'production')
304
+ puts "Scoped valid: #{YourModel.verified_identifier?(scoped_vid, scope: 'production')}"
305
+ puts "Wrong scope: #{YourModel.verified_identifier?(scoped_vid, scope: 'development')}"
306
+ ```
@@ -0,0 +1,110 @@
1
+ # Migrating Guide: Security Features (v2.0.0-pre5)
2
+
3
+ This guide covers adopting the security enhancements introduced in v2.0.0-pre5.
4
+
5
+ ## Security Feature Adoption
6
+
7
+ ### 1. Configure Encryption Keys
8
+
9
+ Before using encrypted fields, configure encryption keys:
10
+
11
+ ```ruby
12
+ Familia.configure do |config|
13
+ config.encryption_keys = {
14
+ v1: 'your-32-byte-base64-encoded-key==',
15
+ v2: 'newer-32-byte-base64-encoded-key=='
16
+ }
17
+ config.current_key_version = :v2
18
+ end
19
+ ```
20
+
21
+ **Key Management:**
22
+ - Use secure key storage (environment variables, key management services)
23
+ - Rotate keys regularly by adding new versions
24
+ - Never remove old key versions while data exists
25
+
26
+ ### 2. Identify Sensitive Fields
27
+
28
+ Mark fields that contain sensitive data:
29
+
30
+ **For Encryption:**
31
+ ```ruby
32
+ class Vault < Familia::Horreum
33
+ feature :encrypted_fields
34
+
35
+ field :name # Plaintext
36
+ encrypted_field :secret_key # Encrypted at rest
37
+ encrypted_field :api_token # Transparent access
38
+ end
39
+ ```
40
+
41
+ **For Transient Fields:**
42
+ ```ruby
43
+ class User < Familia::Horreum
44
+ feature :transient_fields
45
+
46
+ field :email # Persisted
47
+ transient_field :password # Never persisted
48
+ transient_field :session_token # Runtime only
49
+ end
50
+ ```
51
+
52
+ ### 3. Update Serialization Code
53
+
54
+ Handle `RedactedString` in serialization:
55
+
56
+ **Before:**
57
+ ```ruby
58
+ def to_json
59
+ { name: name, password: password }.to_json
60
+ end
61
+ ```
62
+
63
+ **After:**
64
+ ```ruby
65
+ def to_json
66
+ # RedactedString automatically excluded from serialization
67
+ { name: name }.to_json # password field omitted if transient
68
+ end
69
+ ```
70
+
71
+ **Manual RedactedString Handling:**
72
+ ```ruby
73
+ # Access original value when needed
74
+ password.reveal # Returns actual string value
75
+ password.redacted? # Returns true if redacted
76
+ ```
77
+
78
+ ### 4. Implement Key Rotation Procedures
79
+
80
+ **Rotation Process:**
81
+ 1. Add new key version to configuration
82
+ 2. Update `current_key_version`
83
+ 3. Re-encrypt existing data gradually
84
+ 4. Remove old keys after migration complete
85
+
86
+ **Example Rotation Script:**
87
+ ```ruby
88
+ # Add new key version
89
+ Familia.config.encryption_keys[:v3] = 'new-key'
90
+ Familia.config.current_key_version = :v3
91
+
92
+ # Re-encrypt existing records
93
+ Vault.all.each do |vault|
94
+ vault.save # Automatically uses new key version
95
+ end
96
+ ```
97
+
98
+ ## Security Best Practices
99
+
100
+ - **Environment Variables:** Store keys in environment variables, not code
101
+ - **Key Rotation:** Rotate encryption keys regularly (quarterly/annually)
102
+ - **Field Selection:** Only encrypt fields that truly need protection
103
+ - **Memory Clearing:** Use transient fields for temporary sensitive data
104
+ - **Logging:** Verify RedactedString prevents accidental logging
105
+
106
+ ## Next Steps
107
+
108
+ After implementing security features:
109
+ 1. Review [Architecture Migration](v2.0.0-pre6.md) for persistence improvements
110
+ 2. Explore [Relationships Migration](v2.0.0-pre7.md) for the relationship system