mongoid 9.1.1 → 9.1.3

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 (85) hide show
  1. checksums.yaml +4 -4
  2. data/lib/config/locales/en.yml +44 -11
  3. data/lib/mongoid/association/accessors.rb +21 -4
  4. data/lib/mongoid/association/eager_load/discriminated_inclusion.rb +10 -10
  5. data/lib/mongoid/association/eager_load/embedded_distributor.rb +6 -6
  6. data/lib/mongoid/association/eager_load/lookup_pipeline.rb +1 -1
  7. data/lib/mongoid/association/eager_loadable.rb +8 -1
  8. data/lib/mongoid/association/embedded/batchable.rb +17 -1
  9. data/lib/mongoid/association/nested/many.rb +1 -1
  10. data/lib/mongoid/association/referenced/belongs_to/buildable.rb +19 -15
  11. data/lib/mongoid/association/referenced/belongs_to.rb +11 -3
  12. data/lib/mongoid/association/referenced/has_and_belongs_to_many/buildable.rb +25 -5
  13. data/lib/mongoid/association/referenced/has_and_belongs_to_many.rb +12 -0
  14. data/lib/mongoid/association/referenced/has_many/buildable.rb +17 -7
  15. data/lib/mongoid/association/referenced/has_many/proxy.rb +4 -2
  16. data/lib/mongoid/association/referenced/has_one/buildable.rb +20 -6
  17. data/lib/mongoid/association/relatable.rb +18 -0
  18. data/lib/mongoid/association.rb +23 -0
  19. data/lib/mongoid/atomic/modifiers.rb +100 -16
  20. data/lib/mongoid/attributes/readonly.rb +19 -1
  21. data/lib/mongoid/changeable.rb +19 -1
  22. data/lib/mongoid/clients/factory.rb +2 -0
  23. data/lib/mongoid/config/encryption.rb +152 -19
  24. data/lib/mongoid/contextual/none.rb +51 -0
  25. data/lib/mongoid/criteria/scopable.rb +5 -0
  26. data/lib/mongoid/criteria.rb +45 -1
  27. data/lib/mongoid/document.rb +13 -0
  28. data/lib/mongoid/encryptable.rb +43 -16
  29. data/lib/mongoid/errors/invalid_encrypted_association.rb +28 -0
  30. data/lib/mongoid/errors/invalid_encryption_schema.rb +27 -0
  31. data/lib/mongoid/errors/no_encryption_schema.rb +5 -3
  32. data/lib/mongoid/errors.rb +2 -0
  33. data/lib/mongoid/factory.rb +1 -1
  34. data/lib/mongoid/fields/encrypted.rb +14 -3
  35. data/lib/mongoid/fields/foreign_key.rb +9 -0
  36. data/lib/mongoid/fields/standard.rb +10 -0
  37. data/lib/mongoid/fields/validators/macro.rb +29 -0
  38. data/lib/mongoid/fields.rb +49 -2
  39. data/lib/mongoid/persistable/creatable.rb +120 -14
  40. data/lib/mongoid/persistable.rb +15 -15
  41. data/lib/mongoid/persistence_context.rb +46 -4
  42. data/lib/mongoid/reloadable.rb +1 -0
  43. data/lib/mongoid/search_indexable.rb +5 -1
  44. data/lib/mongoid/tasks/database.rb +10 -7
  45. data/lib/mongoid/touchable.rb +28 -1
  46. data/lib/mongoid/version.rb +1 -1
  47. data/lib/mongoid/warnings.rb +4 -0
  48. data/spec/integration/associations/embedded_delayed_atomic_sets_spec.rb +216 -0
  49. data/spec/integration/associations/has_and_belongs_to_many_spec.rb +14 -0
  50. data/spec/integration/atomic/modifiers_spec.rb +283 -0
  51. data/spec/integration/encryption_spec.rb +418 -0
  52. data/spec/mongoid/association/accessors_spec.rb +35 -0
  53. data/spec/mongoid/association/referenced/belongs_to/buildable_spec.rb +35 -6
  54. data/spec/mongoid/association/referenced/encrypted_foreign_key_spec.rb +142 -0
  55. data/spec/mongoid/association/referenced/has_and_belongs_to_many/buildable_spec.rb +36 -5
  56. data/spec/mongoid/association/referenced/has_and_belongs_to_many/proxy_spec.rb +48 -0
  57. data/spec/mongoid/association/referenced/has_many/buildable_spec.rb +24 -6
  58. data/spec/mongoid/association/referenced/has_many/proxy_spec.rb +81 -0
  59. data/spec/mongoid/association/referenced/has_one/buildable_spec.rb +18 -3
  60. data/spec/mongoid/atomic/modifiers_spec.rb +347 -0
  61. data/spec/mongoid/attributes/nested_spec.rb +29 -0
  62. data/spec/mongoid/attributes/readonly_dotted_spec.rb +334 -0
  63. data/spec/mongoid/attributes/readonly_spec.rb +389 -0
  64. data/spec/mongoid/changeable_spec.rb +18 -0
  65. data/spec/mongoid/clients/factory_spec.rb +36 -0
  66. data/spec/mongoid/config/encryption_spec.rb +450 -0
  67. data/spec/mongoid/contextual/none_spec.rb +18 -0
  68. data/spec/mongoid/criteria/includable_spec.rb +346 -0
  69. data/spec/mongoid/criteria_spec.rb +17 -0
  70. data/spec/mongoid/encryptable_spec.rb +54 -0
  71. data/spec/mongoid/factory_spec.rb +8 -0
  72. data/spec/mongoid/fields_spec.rb +37 -0
  73. data/spec/mongoid/findable_spec.rb +14 -0
  74. data/spec/mongoid/scopable_spec.rb +102 -0
  75. data/spec/mongoid/search_indexable_spec.rb +26 -0
  76. data/spec/mongoid/tasks/database_spec.rb +13 -0
  77. data/spec/mongoid/touchable_spec.rb +217 -0
  78. data/spec/mongoid/touchable_spec_models.rb +37 -0
  79. data/spec/support/crypt/models.rb +138 -0
  80. data/spec/support/models/delete_all_account.rb +10 -0
  81. data/spec/support/models/delete_all_item.rb +9 -0
  82. data/spec/support/models/delete_all_scoped_item.rb +11 -0
  83. data/spec/support/models/delete_all_tag.rb +7 -0
  84. data/spec/support/models/modifier_models.rb +65 -0
  85. metadata +2045 -2008
@@ -34,23 +34,33 @@ describe 'Encryption' do
34
34
  Mongoid.default_client[Crypt::Patient.collection_name].drop
35
35
  Mongoid.default_client[Crypt::Car.collection_name].drop
36
36
  Mongoid.default_client[Crypt::Folder.collection_name].drop
37
+ Mongoid.default_client[Crypt::Dossier.collection_name].drop
38
+ Mongoid.default_client[Crypt::Archive.collection_name].drop
37
39
  existing_key_id = Crypt::Patient.encrypt_metadata[:key_id]
38
40
  Crypt::Patient.set_key_id(data_key_id)
39
41
  Crypt::Car.set_key_id(data_key_id)
40
42
  Crypt::Note.set_key_id(data_key_id)
43
+ Crypt::Dossier.set_key_id(data_key_id)
44
+ Crypt::Archive.set_key_id(data_key_id)
41
45
  Mongoid::Config.send(:clients=, config)
42
46
  Mongoid::Clients.with_name(:key_vault)[key_vault_collection].drop
43
47
  Crypt::Patient.store_in(client: :encrypted)
44
48
  Crypt::Car.store_in(client: :encrypted, database: Crypt::Car.storage_options[:database])
45
49
  Crypt::Folder.store_in(client: :encrypted)
50
+ Crypt::Dossier.store_in(client: :encrypted)
51
+ Crypt::Archive.store_in(client: :encrypted)
46
52
 
47
53
  example.run
48
54
 
49
55
  Crypt::Patient.reset_storage_options!
50
56
  Crypt::Folder.reset_storage_options!
57
+ Crypt::Dossier.reset_storage_options!
58
+ Crypt::Archive.reset_storage_options!
51
59
  Crypt::Patient.set_key_id(existing_key_id)
52
60
  Crypt::Car.set_key_id(existing_key_id)
53
61
  Crypt::Note.set_key_id(existing_key_id)
62
+ Crypt::Dossier.set_key_id(existing_key_id)
63
+ Crypt::Archive.set_key_id(existing_key_id)
54
64
  end
55
65
 
56
66
  it 'encrypts and decrypts fields' do
@@ -101,6 +111,27 @@ describe 'Encryption' do
101
111
  end
102
112
  end
103
113
 
114
+ # The document is persisted under the store_as key, not the association
115
+ # name, so the schema has to be keyed by it or the field is stored in the
116
+ # clear.
117
+ it 'stores an embedded field encrypted when the association uses store_as' do
118
+ dossier = Crypt::Dossier.create!(secret: Crypt::DossierSecret.new(token: 'SECRET'))
119
+ unencrypted_client[Crypt::Dossier.collection.name].find(_id: dossier.id).first.tap do |doc|
120
+ expect(doc['s']['token']).to be_a(BSON::Binary)
121
+ expect(doc['s']['token'].type).to eq(:ciphertext)
122
+ end
123
+ expect(Crypt::Dossier.find(dossier.id).secret.token).to eq('SECRET')
124
+ end
125
+
126
+ it 'stores a nested embedded field encrypted when the associations use store_as' do
127
+ archive = Crypt::Archive.create!(entry: Crypt::ArchiveEntry.new(payload: Crypt::ArchivePayload.new(token: 'SECRET')))
128
+ unencrypted_client[Crypt::Archive.collection.name].find(_id: archive.id).first.tap do |doc|
129
+ expect(doc['e']['p']['token']).to be_a(BSON::Binary)
130
+ expect(doc['e']['p']['token'].type).to eq(:ciphertext)
131
+ end
132
+ expect(Crypt::Archive.find(archive.id).entry.payload.token).to eq('SECRET')
133
+ end
134
+
104
135
  it 'stores data encrypted in the non-default database' do
105
136
  car = Crypt::Car.create!(vin: 'VA1234')
106
137
  unencrypted_client
@@ -245,4 +276,391 @@ describe 'Encryption' do
245
276
  end
246
277
  end
247
278
  end
279
+
280
+ # The schema map has one entry per namespace, and it has to cover every model
281
+ # that writes there: models sharing a collection, subclasses, and subclasses
282
+ # of embedded models. Documents are read back through a client without
283
+ # automatic encryption, to see what is actually stored.
284
+ describe 'when more than one model writes to a namespace' do
285
+ let(:root_models) do
286
+ [ Crypt::Badge, Crypt::BadgeScan, Crypt::Member, Crypt::Listing, Crypt::Box, Crypt::Locker ]
287
+ end
288
+
289
+ let(:keyed_models) do
290
+ [ Crypt::Badge, Crypt::BadgeScan, Crypt::Member, Crypt::PrivateListing, Crypt::Box, Crypt::SecretContent ]
291
+ end
292
+
293
+ around do |example|
294
+ original_options = root_models.to_h { |model| [ model, model.storage_options ] }
295
+ existing_key_ids = keyed_models.to_h { |model| [ model, model.encrypt_metadata[:key_id] ] }
296
+ keyed_models.each { |model| model.set_key_id(data_key_id) }
297
+ root_models.each do |model|
298
+ unencrypted_client[model.collection_name.to_s].drop
299
+ model.store_in(client: :encrypted)
300
+ end
301
+ # The schema map is generated when the client is built, so the client has
302
+ # to be built after the key ids above are in place.
303
+ Mongoid::Clients.clear
304
+
305
+ example.run
306
+
307
+ original_options.each { |model, options| model.storage_options = options }
308
+ existing_key_ids.each { |model, key_id| model.set_key_id(key_id) }
309
+ Mongoid::Clients.clear
310
+ end
311
+
312
+ def stored_document(model, id)
313
+ unencrypted_client[model.collection_name.to_s].find(_id: id).first
314
+ end
315
+
316
+ def expect_ciphertext(value)
317
+ expect(value).to be_a(BSON::Binary).and(have_attributes(type: :ciphertext))
318
+ end
319
+
320
+ context 'when two models are stored in one collection' do
321
+ it 'stores the fields of both models encrypted', :aggregate_failures do
322
+ badge = Crypt::Badge.create!(serial: 'SERIAL-1')
323
+ scan = Crypt::BadgeScan.create!(holder: 'HOLDER-1')
324
+
325
+ expect_ciphertext(stored_document(Crypt::Badge, badge.id)['serial'])
326
+ expect_ciphertext(stored_document(Crypt::BadgeScan, scan.id)['holder'])
327
+ end
328
+ end
329
+
330
+ context 'when a subclass adds an encrypted field to an encrypted parent' do
331
+ it 'stores the fields of the parent and of the subclass encrypted', :aggregate_failures do
332
+ employee = Crypt::Employee.create!(ssn: 'SSN-1', salary: 'SALARY-1')
333
+
334
+ stored_document(Crypt::Member, employee.id).tap do |doc|
335
+ expect_ciphertext(doc['ssn'])
336
+ expect_ciphertext(doc['salary'])
337
+ end
338
+ end
339
+
340
+ it 'stores the fields of a sibling subclass encrypted' do
341
+ contractor = Crypt::Contractor.create!(ssn: 'SSN-2', rate: 'RATE-1')
342
+
343
+ expect_ciphertext(stored_document(Crypt::Member, contractor.id)['rate'])
344
+ end
345
+
346
+ it 'reads the fields back' do
347
+ employee = Crypt::Employee.create!(ssn: 'SSN-3', salary: 'SALARY-3')
348
+
349
+ expect(Crypt::Member.find(employee.id).salary).to eq('SALARY-3')
350
+ end
351
+ end
352
+
353
+ context 'when only a subclass has encrypted fields' do
354
+ it 'stores the fields of the subclass encrypted' do
355
+ listing = Crypt::PrivateListing.create!(title: 'TITLE-1', owner_ssn: 'SSN-4')
356
+
357
+ expect_ciphertext(stored_document(Crypt::Listing, listing.id)['owner_ssn'])
358
+ end
359
+ end
360
+
361
+ context 'when a subclass of an embeds_one target adds an encrypted field' do
362
+ it 'stores the fields of the target and of the subclass encrypted', :aggregate_failures do
363
+ box = Crypt::Box.create!(item: Crypt::SealedItem.new(label: 'LABEL-1', seal: 'SEAL-1'))
364
+
365
+ stored_document(Crypt::Box, box.id)['item'].tap do |item|
366
+ expect_ciphertext(item['label'])
367
+ expect_ciphertext(item['seal'])
368
+ end
369
+ end
370
+ end
371
+
372
+ context 'when only a subclass of an embeds_one target has encrypted fields' do
373
+ it 'stores the fields of the subclass encrypted' do
374
+ locker = Crypt::Locker.create!(content: Crypt::SecretContent.new(label: 'LABEL-2', code: 'CODE-1'))
375
+
376
+ expect_ciphertext(stored_document(Crypt::Locker, locker.id)['content']['code'])
377
+ end
378
+ end
379
+
380
+ # An entry for the namespace exists, but it does not cover every encrypted
381
+ # field of the model. The driver encrypts what the entry lists and writes
382
+ # the rest in plaintext.
383
+ context 'when the schema entry for the namespace misses an encrypted field' do
384
+ let(:config) do
385
+ super().merge(
386
+ partial: {
387
+ hosts: SpecConfig.instance.addresses,
388
+ database: database_id,
389
+ options: {
390
+ auto_encryption_options: {
391
+ key_vault_client: :key_vault,
392
+ kms_providers: kms_providers,
393
+ key_vault_namespace: key_vault_namespace,
394
+ extra_options: extra_options,
395
+ schema_map: partial_schema_map
396
+ }
397
+ }
398
+ }
399
+ )
400
+ end
401
+
402
+ let(:partial_schema_map) do
403
+ {
404
+ "#{database_id}.#{Crypt::Member.collection_name}" => {
405
+ 'bsonType' => 'object',
406
+ 'encryptMetadata' => {
407
+ 'keyId' => [ BSON::Binary.new(Base64.decode64(data_key_id), :uuid) ],
408
+ 'algorithm' => 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic'
409
+ },
410
+ 'properties' => {
411
+ 'ssn' => { 'encrypt' => { 'bsonType' => 'string' } }
412
+ }
413
+ }
414
+ }
415
+ end
416
+
417
+ it 'does not store the field in plaintext', :aggregate_failures do
418
+ expect do
419
+ Crypt::Employee.with(client: :partial) { |klass| klass.create!(ssn: 'SSN-5', salary: 'PARTIAL-1') }
420
+ end.to raise_error(Mongoid::Errors::NoEncryptionSchema)
421
+
422
+ expect(
423
+ unencrypted_client[Crypt::Member.collection_name.to_s].find(salary: 'PARTIAL-1').to_a
424
+ ).to be_empty
425
+ end
426
+ end
427
+ end
428
+
429
+ describe 'an encrypted belongs_to foreign key' do
430
+ let(:foreign_key_models) { [] }
431
+
432
+ let(:owner_class) do
433
+ klass = stub_const('Crypt::ForeignKeyOwner', Class.new)
434
+ klass.include(Mongoid::Document)
435
+ foreign_key_models << klass
436
+ klass
437
+ end
438
+
439
+ let(:reference_class) do
440
+ owner_class
441
+ klass = stub_const('Crypt::ForeignKeyReference', Class.new)
442
+ klass.include(Mongoid::Document)
443
+ foreign_key_models << klass
444
+ klass.encrypt_with(key_id: data_key_id) if deterministic
445
+ klass.store_in(client: :encrypted)
446
+ association_options = { class_name: 'Crypt::ForeignKeyOwner', inverse_of: nil }
447
+ association_options[:foreign_key] = foreign_key if foreign_key != :owner_id
448
+ encryption_options = { deterministic: deterministic }
449
+ encryption_options[:key_id] = data_key_id unless deterministic
450
+
451
+ klass.field(foreign_key, type: BSON::ObjectId, encrypt: encryption_options)
452
+ klass.belongs_to(:owner, association_options)
453
+
454
+ # The schema map is built when the client is constructed.
455
+ Mongoid::Clients.clear
456
+ klass
457
+ end
458
+
459
+ after do
460
+ foreign_key_models.each { |model| Mongoid.deregister_model(model) }
461
+ Mongoid::Clients.clear
462
+ end
463
+
464
+ foreign_keys = %i[owner_id secret_owner_id]
465
+ [ true, false ].each do |deterministic|
466
+ foreign_keys.each do |foreign_key|
467
+ key_type = (foreign_key == :owner_id) ? 'default' : 'custom'
468
+ context "with #{deterministic ? 'deterministic' : 'random'} encryption and the " \
469
+ "#{key_type} foreign key" do
470
+ let(:deterministic) { deterministic }
471
+ let(:foreign_key) { foreign_key }
472
+
473
+ it 'encrypts the key and preserves association behavior', :aggregate_failures do
474
+ owner = owner_class.create!
475
+ other_owner = owner_class.create!
476
+ reference = reference_class.create!(owner: owner)
477
+ same_owner = reference_class.create!(owner: owner)
478
+ collection = unencrypted_client[reference_class.collection_name.to_s]
479
+
480
+ stored = collection.find(_id: reference.id).first
481
+ expect(stored[foreign_key.to_s]).to be_a(BSON::Binary).and(have_attributes(type: :ciphertext))
482
+ other_ciphertext = collection.find(_id: same_owner.id).first[foreign_key.to_s]
483
+ if deterministic
484
+ expect(stored[foreign_key.to_s]).to eq(other_ciphertext)
485
+ else
486
+ expect(stored[foreign_key.to_s]).not_to eq(other_ciphertext)
487
+ end
488
+
489
+ reference.reload
490
+ expect(reference.public_send(foreign_key)).to eq(owner.id)
491
+ expect(reference.owner.id).to eq(owner.id)
492
+
493
+ # Assigning the foreign key must also invalidate the cached association.
494
+ reference.public_send("#{foreign_key}=", other_owner.id)
495
+ expect(reference.owner.id).to eq(other_owner.id)
496
+ reference.save!
497
+
498
+ stored = collection.find(_id: reference.id).first
499
+ expect(stored[foreign_key.to_s]).to be_a(BSON::Binary).and(have_attributes(type: :ciphertext))
500
+ expect(reference.reload.owner.id).to eq(other_owner.id)
501
+ end
502
+ end
503
+ end
504
+ end
505
+ end
506
+
507
+ # A belongs_to declared on a parent generates the foreign key on the whole
508
+ # hierarchy. An encrypted declaration of that key on a subclass must survive
509
+ # the propagation, or the subclass silently loses its encryption.
510
+ describe 'an encrypted belongs_to foreign key declared on a subclass' do
511
+ let(:models) { [] }
512
+
513
+ let(:owner_class) do
514
+ klass = stub_const('Crypt::InheritedForeignKeyOwner', Class.new)
515
+ klass.include(Mongoid::Document)
516
+ models << klass
517
+ klass
518
+ end
519
+
520
+ let(:parent_class) do
521
+ klass = stub_const('Crypt::InheritedForeignKeyParent', Class.new)
522
+ klass.include(Mongoid::Document)
523
+ models << klass
524
+ klass
525
+ end
526
+
527
+ let(:child_class) do
528
+ parent_class
529
+ klass = stub_const('Crypt::InheritedForeignKeyChild', Class.new(parent_class))
530
+ models << klass
531
+ klass.store_in(client: :encrypted)
532
+ klass.encrypt_with(key_id: data_key_id) if model_key
533
+ klass.field(foreign_key, type: BSON::ObjectId, encrypt: encryption_options)
534
+ klass.belongs_to(:owner, association_options) if child_association
535
+ klass
536
+ end
537
+
538
+ let(:association_options) do
539
+ { class_name: 'Crypt::InheritedForeignKeyOwner', inverse_of: nil }.tap do |options|
540
+ options[:foreign_key] = foreign_key if foreign_key != :owner_id
541
+ end
542
+ end
543
+
544
+ let(:encryption_options) do
545
+ { deterministic: deterministic }.tap do |options|
546
+ options[:key_id] = data_key_id unless model_key
547
+ end
548
+ end
549
+
550
+ let(:algorithm) do
551
+ if deterministic
552
+ 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic'
553
+ else
554
+ 'AEAD_AES_256_CBC_HMAC_SHA_512-Random'
555
+ end
556
+ end
557
+
558
+ before do
559
+ child_class
560
+ parent_class.belongs_to(:owner, association_options)
561
+ # The schema map is built when the client is constructed.
562
+ Mongoid::Clients.clear
563
+ end
564
+
565
+ after do
566
+ models.each { |model| Mongoid.deregister_model(model) }
567
+ Mongoid::Clients.clear
568
+ end
569
+
570
+ shared_examples 'an encrypted inherited foreign key' do
571
+ it 'keeps the encryption on the subclass and supports the association', :aggregate_failures do
572
+ field = child_class.fields[foreign_key.to_s]
573
+ expect(field).to be_a(Mongoid::Fields::EncryptedForeignKey)
574
+ expect(field).to be_foreign_key
575
+ expect(field.type).to eq(BSON::ObjectId)
576
+ expect(field.options[:encrypt]).to eq(encryption_options)
577
+ expect(field.deterministic?).to eq(deterministic)
578
+ if model_key
579
+ expect(field.key_id).to be_nil
580
+ else
581
+ expect(field.key_id).to eq(data_key_id)
582
+ end
583
+ expect(child_class.encrypted?).to be true
584
+ expect(parent_class.encrypted?).to be false
585
+
586
+ # The classes share a collection, and only the subclass contributes an
587
+ # entry to the schema map for it.
588
+ expect(child_class.collection_name).to eq(parent_class.collection_name)
589
+ schema = Mongoid.config.encryption_schema_map(
590
+ database_id, [ parent_class, child_class ]
591
+ ).fetch("#{database_id}.#{child_class.collection_name}")
592
+ encryption = schema.dig('properties', foreign_key.to_s, 'encrypt')
593
+ expect(encryption['bsonType']).to eq('objectId')
594
+ expect(encryption['algorithm']).to eq(algorithm)
595
+ if model_key
596
+ expect(encryption).not_to have_key('keyId')
597
+ expect(schema.dig('encryptMetadata', 'keyId')).to be_a(Array)
598
+ else
599
+ expect(encryption['keyId']).to be_a(Array)
600
+ end
601
+
602
+ owner = owner_class.create!
603
+ other_owner = owner_class.create!
604
+ child = child_class.create!(owner: owner)
605
+ same_owner = child_class.create!(owner: owner)
606
+ collection = unencrypted_client[child_class.collection_name.to_s]
607
+
608
+ stored = collection.find(_id: child.id).first
609
+ expect(stored[foreign_key.to_s]).to be_a(BSON::Binary).and(have_attributes(type: :ciphertext))
610
+ other_ciphertext = collection.find(_id: same_owner.id).first[foreign_key.to_s]
611
+ if deterministic
612
+ expect(stored[foreign_key.to_s]).to eq(other_ciphertext)
613
+ else
614
+ expect(stored[foreign_key.to_s]).not_to eq(other_ciphertext)
615
+ end
616
+
617
+ child.reload
618
+ expect(child.public_send(foreign_key)).to eq(owner.id)
619
+ expect(child.owner.id).to eq(owner.id)
620
+
621
+ child.public_send("#{foreign_key}=", other_owner.id)
622
+ expect(child.owner.id).to eq(other_owner.id)
623
+ end
624
+ end
625
+
626
+ context 'when only the subclass declares the field' do
627
+ let(:child_association) { false }
628
+
629
+ context 'with deterministic encryption and the default foreign key' do
630
+ let(:deterministic) { true }
631
+ let(:model_key) { false }
632
+ let(:foreign_key) { :owner_id }
633
+
634
+ it_behaves_like 'an encrypted inherited foreign key'
635
+ end
636
+
637
+ context 'with random encryption, a custom foreign key and a model-level key' do
638
+ let(:deterministic) { false }
639
+ let(:model_key) { true }
640
+ let(:foreign_key) { :secret_owner_id }
641
+
642
+ it_behaves_like 'an encrypted inherited foreign key'
643
+ end
644
+ end
645
+
646
+ context 'when the subclass also declares the association' do
647
+ let(:child_association) { true }
648
+
649
+ context 'with deterministic encryption, a custom foreign key and a model-level key' do
650
+ let(:deterministic) { true }
651
+ let(:model_key) { true }
652
+ let(:foreign_key) { :secret_owner_id }
653
+
654
+ it_behaves_like 'an encrypted inherited foreign key'
655
+ end
656
+
657
+ context 'with random encryption and the default foreign key' do
658
+ let(:deterministic) { false }
659
+ let(:model_key) { false }
660
+ let(:foreign_key) { :owner_id }
661
+
662
+ it_behaves_like 'an encrypted inherited foreign key'
663
+ end
664
+ end
665
+ end
248
666
  end
@@ -689,6 +689,41 @@ describe Mongoid::Association::Accessors do
689
689
  end
690
690
  end
691
691
  end
692
+
693
+ context 'when the document has a stored field named like a referenced association' do
694
+ before(:all) do
695
+ class Musician
696
+ include Mongoid::Document
697
+
698
+ belongs_to :orchestra, optional: true
699
+ end
700
+
701
+ class Orchestra
702
+ include Mongoid::Document
703
+
704
+ has_many :musicians
705
+ end
706
+ end
707
+
708
+ after(:all) do
709
+ Object.send(:remove_const, :Orchestra)
710
+ Object.send(:remove_const, :Musician)
711
+ end
712
+
713
+ # The musicians used to be embedded, so the stored orchestra still holds
714
+ # the old array under the association's name.
715
+ let!(:orchestra_id) do
716
+ BSON::ObjectId.new.tap do |id|
717
+ Orchestra.collection.insert_one('_id' => id, 'musicians' => [ { '_id' => BSON::ObjectId.new } ])
718
+ end
719
+ end
720
+
721
+ let!(:musician) { Musician.create!(orchestra_id: orchestra_id) }
722
+
723
+ it 'loads the association by its key' do
724
+ expect(Orchestra.find(orchestra_id).musicians.to_a).to eq([ musician ])
725
+ end
726
+ end
692
727
  end
693
728
 
694
729
  context 'when setting associations to empty values' do
@@ -122,21 +122,50 @@ describe Mongoid::Association::Referenced::BelongsTo::Buildable do
122
122
  end
123
123
  end
124
124
 
125
- context 'when provided an array of hashes' do
125
+ context 'when provided preloaded documents' do
126
126
  let(:object) do
127
- [
128
- { '_id' => BSON::ObjectId.new, 'username' => 'user1' },
129
- { '_id' => BSON::ObjectId.new, 'username' => 'user2' }
130
- ]
127
+ Mongoid::Association::PreloadedDocuments.new(
128
+ [
129
+ { '_id' => BSON::ObjectId.new, 'username' => 'user1' },
130
+ { '_id' => BSON::ObjectId.new, 'username' => 'user2' }
131
+ ]
132
+ )
131
133
  end
132
134
 
133
- it 'queries and returns the document' do
135
+ it 'returns the preloaded document' do
134
136
  first_doc = document
135
137
  expect(first_doc).to be_a(Person)
136
138
  expect(first_doc.username).to eq('user1')
137
139
  end
138
140
  end
139
141
 
142
+ context 'when the foreign key is supplied as attributes' do
143
+ it 'does not build a document from a hash-valued foreign key' do
144
+ game = Game.new(person_id: { '_id' => BSON::ObjectId.new, '_type' => 'Canvas' })
145
+
146
+ expect(game.person).to be_nil
147
+ end
148
+
149
+ it 'does not build a document from an array-valued foreign key' do
150
+ game = Game.new(person_id: [ { '_id' => BSON::ObjectId.new, '_type' => 'Canvas' } ])
151
+
152
+ expect(game.person).to be_nil
153
+ end
154
+
155
+ it 'does not build a document from a stored hash-valued foreign key' do
156
+ game = Game.new(person_id: { '_id' => BSON::ObjectId.new, '_type' => 'Canvas' })
157
+ game.save!(validate: false)
158
+
159
+ expect(Game.find(game.id).person).to be_nil
160
+ end
161
+
162
+ it 'does not treat an array of ids as a lookup result' do
163
+ game = Game.new(person_id: [ BSON::ObjectId.new ])
164
+
165
+ expect { game.person }.not_to raise_error
166
+ end
167
+ end
168
+
140
169
  context 'when provided a object' do
141
170
  let!(:person) do
142
171
  Person.create!
@@ -0,0 +1,142 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'spec_helper'
4
+
5
+ describe 'Encrypted has_and_belongs_to_many foreign keys' do
6
+ let(:model) do
7
+ klass = stub_const('ForeignKeyHabtmMember', Class.new)
8
+ klass.include(Mongoid::Document)
9
+ klass
10
+ end
11
+
12
+ after do
13
+ Mongoid.deregister_model(model)
14
+ end
15
+
16
+ [ true, { deterministic: true }, { deterministic: false } ].each do |encryption|
17
+ context "with encrypt: #{encryption.inspect}" do
18
+ it 'rejects the association when its foreign key is already encrypted' do
19
+ model.field(:secret_group_ids, type: Array, encrypt: encryption)
20
+
21
+ expect do
22
+ model.has_and_belongs_to_many(:groups, foreign_key: :secret_group_ids, inverse_of: nil)
23
+ end.to raise_error(Mongoid::Errors::InvalidEncryptedAssociation, /encrypt/i)
24
+ end
25
+
26
+ it 'rejects encryption when the foreign key already belongs to an association' do
27
+ model.has_and_belongs_to_many(:groups, inverse_of: nil)
28
+
29
+ expect do
30
+ model.field(:group_ids, type: Array, encrypt: encryption)
31
+ end.to raise_error(Mongoid::Errors::InvalidEncryptedAssociation, /encrypt/i)
32
+ end
33
+ end
34
+ end
35
+
36
+ it 'allows an unencrypted foreign key' do
37
+ model.field(:group_ids, type: Array)
38
+
39
+ expect do
40
+ model.has_and_belongs_to_many(:groups, inverse_of: nil)
41
+ end.not_to raise_error
42
+ end
43
+
44
+ context 'when the encrypted field is declared on a parent model' do
45
+ let(:parent_model) do
46
+ klass = stub_const('ForeignKeyHabtmParent', Class.new)
47
+ klass.include(Mongoid::Document)
48
+ klass
49
+ end
50
+
51
+ let(:custom_foreign_key) { nil }
52
+
53
+ let(:foreign_key) { custom_foreign_key || :group_ids }
54
+
55
+ let(:association_options) do
56
+ { inverse_of: nil }.tap do |options|
57
+ options[:foreign_key] = custom_foreign_key if custom_foreign_key
58
+ end
59
+ end
60
+
61
+ let(:child_model) do
62
+ parent_model
63
+ klass = stub_const('ForeignKeyHabtmChild', Class.new(parent_model))
64
+ klass.has_and_belongs_to_many(:groups, association_options)
65
+ klass
66
+ end
67
+
68
+ after do
69
+ Mongoid.deregister_model(child_model)
70
+ Mongoid.deregister_model(parent_model)
71
+ end
72
+
73
+ encryption_options = [ { deterministic: true }, { deterministic: false } ]
74
+ custom_foreign_keys = [ nil, :secret_group_ids ]
75
+ encryption_options.each do |encryption|
76
+ custom_foreign_keys.each do |custom_key|
77
+ key_type = custom_key ? 'a custom' : 'the default'
78
+ context "with #{encryption.inspect} and #{key_type} foreign key" do
79
+ let(:custom_foreign_key) { custom_key }
80
+
81
+ it 'rejects the field before changing either model' do
82
+ association = child_model.relations['groups']
83
+ existing_field = child_model.fields[foreign_key.to_s]
84
+
85
+ expect do
86
+ parent_model.field(foreign_key, type: Array, encrypt: encryption)
87
+ end.to raise_error(Mongoid::Errors::InvalidEncryptedAssociation, /encrypt/i)
88
+
89
+ expect(parent_model.fields).not_to have_key(foreign_key.to_s)
90
+ expect(child_model.fields[foreign_key.to_s]).to equal(existing_field)
91
+ expect(child_model.fields[foreign_key.to_s]).not_to be_encrypted
92
+ expect(child_model.relations['groups']).to equal(association)
93
+ end
94
+ end
95
+ end
96
+ end
97
+
98
+ it 'allows an encrypted field that no descendant uses as an association key' do
99
+ child_model
100
+
101
+ expect do
102
+ parent_model.field(:secret, type: String, encrypt: { deterministic: true })
103
+ end.not_to raise_error
104
+
105
+ expect(parent_model.fields['secret']).to be_encrypted
106
+ expect(child_model.fields['secret']).to be_encrypted
107
+ end
108
+ end
109
+
110
+ context 'when the encrypted field is declared on a child model' do
111
+ let(:parent_model) do
112
+ klass = stub_const('ForeignKeyHabtmParentWithChildField', Class.new)
113
+ klass.include(Mongoid::Document)
114
+ klass
115
+ end
116
+
117
+ let(:child_model) do
118
+ parent_model
119
+ klass = stub_const('ForeignKeyHabtmChildWithField', Class.new(parent_model))
120
+ klass.field(:group_ids, type: Array, encrypt: { deterministic: false })
121
+ klass
122
+ end
123
+
124
+ after do
125
+ Mongoid.deregister_model(child_model)
126
+ Mongoid.deregister_model(parent_model)
127
+ end
128
+
129
+ it 'rejects the association before changing either model' do
130
+ existing_field = child_model.fields['group_ids']
131
+
132
+ expect do
133
+ parent_model.has_and_belongs_to_many(:groups, inverse_of: nil)
134
+ end.to raise_error(Mongoid::Errors::InvalidEncryptedAssociation, /encrypt/i)
135
+
136
+ expect(parent_model.fields).not_to have_key('group_ids')
137
+ expect(parent_model.relations).not_to have_key('groups')
138
+ expect(child_model.fields['group_ids']).to equal(existing_field)
139
+ expect(child_model.fields['group_ids']).to be_encrypted
140
+ end
141
+ end
142
+ end