melos 0.0.2 → 0.9.0

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 (43) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +71 -11
  3. data/docs/roadmap.md +302 -0
  4. data/docs/validation.md +172 -0
  5. data/lib/melos/capabilities.rb +18 -0
  6. data/lib/melos/client.rb +255 -0
  7. data/lib/melos/credential/x509.rb +91 -0
  8. data/lib/melos/crypto.rb +109 -15
  9. data/lib/melos/epoch_secrets.rb +166 -0
  10. data/lib/melos/errors.rb +18 -0
  11. data/lib/melos/external_sender.rb +78 -0
  12. data/lib/melos/group/validation.rb +310 -0
  13. data/lib/melos/group.rb +1087 -0
  14. data/lib/melos/key_package_bundle.rb +67 -0
  15. data/lib/melos/persistence.rb +45 -0
  16. data/lib/melos/private_tree.rb +70 -0
  17. data/lib/melos/ratchet_tree.rb +407 -0
  18. data/lib/melos/secret_tree.rb +130 -88
  19. data/lib/melos/struct/base.rb +46 -20
  20. data/lib/melos/struct/structs.rb +205 -87
  21. data/lib/melos/tree.rb +4 -120
  22. data/lib/melos/vec.rb +20 -35
  23. data/lib/melos/version.rb +1 -1
  24. data/lib/melos.rb +13 -2
  25. metadata +18 -22
  26. data/lib/melos/key_schedule.rb +0 -62
  27. data/lib/melos/struct/ratchet_tree.rb +0 -324
  28. data/test_vectors/crypto-basics.json +0 -303
  29. data/test_vectors/deserialization.json +0 -58
  30. data/test_vectors/key-schedule.json +0 -926
  31. data/test_vectors/message-protection.json +0 -142
  32. data/test_vectors/messages.json +0 -5702
  33. data/test_vectors/passive-client-handling-commit.json +0 -2683
  34. data/test_vectors/passive-client-random.json +0 -2657
  35. data/test_vectors/passive-client-welcome.json +0 -814
  36. data/test_vectors/psk_secret.json +0 -2382
  37. data/test_vectors/secret-tree.json +0 -4846
  38. data/test_vectors/transcript-hashes.json +0 -58
  39. data/test_vectors/tree-math.json +0 -8276
  40. data/test_vectors/tree-operations.json +0 -47
  41. data/test_vectors/tree-validation.json +0 -11839
  42. data/test_vectors/treekem.json +0 -14877
  43. data/test_vectors/welcome.json +0 -51
@@ -0,0 +1,1087 @@
1
+ require 'securerandom'
2
+ require_relative 'crypto'
3
+ require_relative 'constants'
4
+ require_relative 'vec'
5
+ require_relative 'ratchet_tree'
6
+ require_relative 'private_tree'
7
+ require_relative 'epoch_secrets'
8
+ require_relative 'psk'
9
+ require_relative 'struct/structs'
10
+
11
+ # One member's view of one MLS group (RFC 9420 Sections 8, 11 and 12): the public state every
12
+ # member shares (ratchet tree, extensions, transcript hashes, from which the GroupContext is
13
+ # derived), this member's private state (leaf index, private tree, signature key) and the
14
+ # current epoch's key schedule.
15
+ class Melos::Group
16
+ # a member added by a commit: where it landed in the tree, and the KeyPackage it joins with
17
+ Joiner = Struct.new(:leaf_index, :key_package)
18
+
19
+ # 12.4.2: the state of the next epoch, computed from a Commit but not yet in effect.
20
+ # It is produced by #stage_commit (received commits) or #create_commit (our own) and applied by #merge_commit.
21
+ # removes_us: the Commit removed this member; only ratchet_tree, extensions, joiners and psk_ids are then set
22
+ # reinit: the ReInit the Commit covers (12.1.5), which ends the group once merged
23
+ StagedCommit = Struct.new(
24
+ :ratchet_tree, :private_tree, :extensions, :confirmed_transcript_hash, :interim_transcript_hash,
25
+ :epoch_secrets, :group_context, :confirmation_tag, :joiners, :path_secrets, :psk_ids, :removes_us, :reinit,
26
+ keyword_init: true
27
+ )
28
+
29
+ # the proposal types defined in RFC 9420; any other type is not supported by this implementation (12.2, 13.2)
30
+ KNOWN_PROPOSAL_TYPES = [
31
+ Melos::Constants::ProposalType::ADD, Melos::Constants::ProposalType::UPDATE, Melos::Constants::ProposalType::REMOVE,
32
+ Melos::Constants::ProposalType::PSK, Melos::Constants::ProposalType::REINIT, Melos::Constants::ProposalType::EXTERNAL_INIT,
33
+ Melos::Constants::ProposalType::GROUP_CONTEXT_EXTENSIONS
34
+ ].freeze
35
+
36
+ # what #create_commit produces: the Commit message to send, the Welcome for any joiners (or nil),
37
+ # and the staged state to merge once the Delivery Service has accepted the commit
38
+ CommitResult = Struct.new(:commit, :welcome, :staged, keyword_init: true)
39
+
40
+ # 9.1, 15.3: an epoch that is no longer current, kept so its late application messages can be read:
41
+ # its secret tree and sender data secret, and the GroupContext and tree its senders signed against
42
+ PastEpoch = Struct.new(:epoch_secrets, :group_context, :ratchet_tree, keyword_init: true)
43
+
44
+ # 15.3: how many epochs before the current one keep their secret trees for late application messages
45
+ DEFAULT_MAX_PAST_EPOCHS = 2
46
+
47
+ # 12.1.8: the proposal types an external sender may send; anything else from one is malformed
48
+ EXTERNAL_PROPOSAL_TYPES = [
49
+ Melos::Constants::ProposalType::ADD, Melos::Constants::ProposalType::REMOVE, Melos::Constants::ProposalType::PSK,
50
+ Melos::Constants::ProposalType::REINIT, Melos::Constants::ProposalType::GROUP_CONTEXT_EXTENSIONS
51
+ ].freeze
52
+
53
+ # 12.1.8: external proposals that are not authorized are invalid; which ones are is the application's
54
+ # policy. The default accepts every proposal that passes the protocol's own checks.
55
+ DEFAULT_EXTERNAL_PROPOSAL_VALIDATOR = ->(_authenticated_content) { true }
56
+
57
+ # 8.6: how many epochs' resumption PSKs a group keeps
58
+ DEFAULT_MAX_RESUMPTION_PSKS = 32
59
+
60
+ # 11.2, 11.3: whether two leaves (one in an old group, one in a group resumed from it) are the same
61
+ # member is the application's call; by default, when their credentials are identical
62
+ DEFAULT_MEMBER_MATCHER = ->(old_leaf, new_leaf) { old_leaf.credential.raw == new_leaf.credential.raw }
63
+
64
+ # the options of .create and .from_welcome that configure the secret tree's ratchets (Melos::SecretTree)
65
+ SECRET_TREE_OPTIONS = %i[max_forward_distance out_of_order_tolerance].freeze
66
+
67
+ attr_reader :suite, :group_id, :epoch, :leaf_index, :ratchet_tree, :private_tree, :extensions,
68
+ :confirmed_transcript_hash, :interim_transcript_hash, :epoch_secrets, :resumption_psks, :external_psks,
69
+ :pending_reinit
70
+
71
+ # Use .create or .from_welcome rather than calling this directly.
72
+ # credential_validator: ->(credential, leaf_node) { true/false }, the application's Authentication Service check (5.3.1);
73
+ # the default accepts basic credentials only
74
+ # max_leaf_node_lifetime: longest acceptable Lifetime of a leaf node in seconds (7.2); nil for no limit
75
+ # max_past_epochs: how many earlier epochs still accept application messages (15.3); 0 for none
76
+ # external_proposal_validator: ->(authenticated_content) { true/false }, whether a proposal from an
77
+ # external sender or a new member is authorized (12.1.8)
78
+ # resumption_psk_lookup: ->(group_id, epoch) { psk or nil }, the resumption PSKs of other groups (8.6); Melos::Client supplies it
79
+ # max_resumption_psks: how many epochs' resumption PSKs of this group are kept (8.6)
80
+ # member_matcher: ->(old_leaf, new_leaf) { true/false }, whether two leaves are the same member (11.2, 11.3,
81
+ # and the old and new leaf of a resync external commit, 12.2)
82
+ # .create and .from_welcome also take max_forward_distance: and out_of_order_tolerance: for the
83
+ # secret tree's ratchets (Melos::SecretTree); epochs created by commits inherit them.
84
+ def initialize(suite:, group_id:, epoch:, leaf_index:, signature_private_key:, ratchet_tree:, private_tree:,
85
+ extensions:, confirmed_transcript_hash:, interim_transcript_hash:, epoch_secrets:, external_psks: {},
86
+ credential_validator: DEFAULT_CREDENTIAL_VALIDATOR, max_leaf_node_lifetime: DEFAULT_MAX_LEAF_NODE_LIFETIME,
87
+ max_past_epochs: DEFAULT_MAX_PAST_EPOCHS, external_proposal_validator: DEFAULT_EXTERNAL_PROPOSAL_VALIDATOR,
88
+ resumption_psk_lookup: nil, max_resumption_psks: DEFAULT_MAX_RESUMPTION_PSKS,
89
+ member_matcher: DEFAULT_MEMBER_MATCHER, confirmation_tag: nil)
90
+ @suite = suite
91
+ @group_id = group_id
92
+ @epoch = epoch
93
+ @leaf_index = leaf_index
94
+ @signature_private_key = signature_private_key
95
+ @ratchet_tree = ratchet_tree
96
+ @private_tree = private_tree
97
+ @extensions = extensions
98
+ @confirmed_transcript_hash = confirmed_transcript_hash
99
+ @interim_transcript_hash = interim_transcript_hash
100
+ @epoch_secrets = epoch_secrets
101
+ @external_psks = external_psks # psk_id -> psk
102
+ @credential_validator = credential_validator
103
+ @max_leaf_node_lifetime = max_leaf_node_lifetime
104
+ @max_past_epochs = max_past_epochs
105
+ @external_proposal_validator = external_proposal_validator
106
+ @resumption_psk_lookup = resumption_psk_lookup
107
+ @max_resumption_psks = max_resumption_psks
108
+ @member_matcher = member_matcher
109
+ @confirmation_tag = confirmation_tag # of the Commit that started this epoch (8.2), for GroupInfos (12.4.3)
110
+ @past_epochs = {} # epoch -> PastEpoch, for late application messages (9.1, 15.3)
111
+ @resumption_psks = {} # epoch -> resumption_psk (8.4)
112
+ @resumption_psks[epoch] = epoch_secrets.resumption_psk if epoch_secrets.available?(:resumption_psk)
113
+ @external_joiner = false # true while this is a joiner's view of the epoch before its external commit (12.4.3.2)
114
+ @pending_proposals = {} # ProposalRef -> AuthenticatedContent, sent or received in the current epoch (12.4)
115
+ @pending_updates = {} # encryption_key -> private key, for Update proposals we sent this epoch (12.1.2)
116
+ @group_context = nil
117
+ @active = true # false once a Commit has removed this member (12.4.2) or reinitialized the group (12.1.5)
118
+ @pending_reinit = nil # the ReInit of the last Commit, once merged
119
+ @resumption_override = nil # [PreSharedKeyID.raw, psk] allowed in the initial commit of a reinit or branch
120
+ end
121
+
122
+ # false after a Commit removed this member or covered a ReInit: it can no longer send or follow the
123
+ # group, though #unprotect still works for late messages of the last epoch it was in. After a ReInit,
124
+ # #pending_reinit holds the parameters of the group that replaces this one (Melos::Client#reinit_group).
125
+ def active?
126
+ @active
127
+ end
128
+
129
+ # 6: an MLSMessage's version MUST be mls10
130
+ def self.check_message_version!(mls_message)
131
+ return if mls_message.version == Melos::Constants::Version::MLS10
132
+ raise Melos::ProtocolError.new("unsupported MLS version #{mls_message.version}")
133
+ end
134
+
135
+ # 11: create a group whose only member is this leaf
136
+ # external_psks: psk_id -> psk, for external PSKs that commits may reference
137
+ def self.create(suite, group_id, leaf_node, encryption_private_key:, signature_private_key:, extensions: [], external_psks: {}, **options)
138
+ secret_tree_options = options.slice(*SECRET_TREE_OPTIONS)
139
+ options = options.except(*SECRET_TREE_OPTIONS)
140
+ Melos::Struct::Extension.check_unique_types!(extensions, 'GroupContext extensions')
141
+ ratchet_tree = Melos::RatchetTree.new(suite, [Melos::Struct::Node.new_leaf_node(leaf_node)])
142
+ private_tree = Melos::PrivateTree.new
143
+ private_tree[0] = encryption_private_key
144
+ group_context = Melos::Struct::GroupContext.create(
145
+ cipher_suite: suite.suite_id, group_id: group_id, epoch: 0,
146
+ tree_hash: ratchet_tree.root_tree_hash, confirmed_transcript_hash: '', extensions: extensions
147
+ )
148
+ # 8: epoch 0 is derived from a fresh random init_secret, an all-zero commit secret and no PSKs
149
+ epoch_secrets = Melos::EpochSecrets.from_init_secret(suite, SecureRandom.random_bytes(suite.kdf.n_h), secret_tree_options: secret_tree_options)
150
+ .next(Melos::Crypto::Util.zero_vector(suite.kdf.n_h), Melos::PSK.psk_secret(suite, []), group_context, n_leaves: 1)
151
+ confirmation_tag = Melos::Crypto.mac(suite, epoch_secrets.confirmation_key, '')
152
+ group = new(
153
+ suite: suite, group_id: group_id, epoch: 0, leaf_index: 0, signature_private_key: signature_private_key,
154
+ ratchet_tree: ratchet_tree, private_tree: private_tree, extensions: extensions,
155
+ confirmed_transcript_hash: '', interim_transcript_hash: interim_transcript_hash(suite, '', confirmation_tag),
156
+ epoch_secrets: epoch_secrets.discard_consumed!, external_psks: external_psks, confirmation_tag: confirmation_tag, **options
157
+ )
158
+ group.send(:validate_external_senders!, extensions)
159
+ group
160
+ end
161
+
162
+ # 12.4.3.1: join a group from a Welcome.
163
+ # welcome: a Melos::Struct::MLSMessage carrying a Welcome, or the Welcome itself
164
+ # key_package: the KeyPackage (or MLSMessage carrying it) this member published
165
+ # init_private_key, encryption_private_key: private keys of the KeyPackage's init_key and leaf encryption_key
166
+ # external_psks: psk_id -> psk, for any external PSKs the Welcome references
167
+ # ratchet_tree: serialized tree, if it was delivered outside the Welcome's ratchet_tree extension
168
+ # resumption_psk_lookup: ->(group_id, epoch) { psk or nil }, for resumption PSKs the Welcome references
169
+ # resumed_group_lookup: ->(group_id) { Melos::Group or nil }, the group a reinit or branch Welcome resumes
170
+ # (11.2, 11.3): it is checked against the new group
171
+ # member_matcher: ->(old_leaf, new_leaf) { true/false }, whether two leaves are the same member, for those checks
172
+ def self.from_welcome(suite, welcome, key_package:, init_private_key:, encryption_private_key:, signature_private_key:,
173
+ external_psks: {}, ratchet_tree: nil, resumption_psk_lookup: nil, resumed_group_lookup: nil,
174
+ member_matcher: DEFAULT_MEMBER_MATCHER, **options)
175
+ secret_tree_options = options.slice(*SECRET_TREE_OPTIONS)
176
+ options = options.except(*SECRET_TREE_OPTIONS)
177
+ if welcome.is_a?(Melos::Struct::MLSMessage)
178
+ check_message_version!(welcome)
179
+ welcome = welcome.welcome
180
+ end
181
+ raise ArgumentError.new('not a Welcome message') if welcome.nil?
182
+ raise Melos::ProtocolError.new('Welcome is for a different cipher suite') unless welcome.cipher_suite == suite.suite_id
183
+ key_package = key_package.key_package if key_package.is_a?(Melos::Struct::MLSMessage)
184
+ # 12.4.3.1: the KeyPackage and the Welcome must be for the same cipher suite
185
+ raise Melos::ProtocolError.new('KeyPackage and Welcome are for different cipher suites') unless key_package.cipher_suite == welcome.cipher_suite
186
+
187
+ # Identify the entry in welcome.secrets corresponding to our KeyPackage and decrypt it with init_priv
188
+ key_package_ref = key_package.ref(suite)
189
+ encrypted_group_secrets = welcome.secrets.find { _1.new_member == key_package_ref }&.encrypted_group_secrets
190
+ raise Melos::ProtocolError.new('Welcome has no entry for this KeyPackage') if encrypted_group_secrets.nil?
191
+ group_secrets = Melos::Struct::GroupSecrets.new(
192
+ Melos::Crypto.decrypt_with_label(
193
+ suite, init_private_key, "Welcome", welcome.encrypted_group_info,
194
+ encrypted_group_secrets.kem_output, encrypted_group_secrets.ciphertext
195
+ )
196
+ )
197
+
198
+ # 8.4: the PSKs named in GroupSecrets; 12.4.3.1: at most one of them links to a reinitialized or branched group
199
+ resumed_psk_ids = group_secrets.psks.select(&:reinit_or_branch?)
200
+ raise Melos::ProtocolError.new('Welcome has more than one reinit or branch resumption PSK') if resumed_psk_ids.size > 1
201
+ psks = group_secrets.psks.map do |psk_id|
202
+ value =
203
+ case psk_id.psktype
204
+ when Melos::Constants::PSKType::EXTERNAL
205
+ external_psks.fetch(psk_id.psk_id) { raise Melos::StateError.new('Welcome references an unknown external PSK') }
206
+ when Melos::Constants::PSKType::RESUMPTION
207
+ check_resumption_usage!(psk_id)
208
+ resumption_psk_lookup&.call(psk_id.psk_group_id, psk_id.psk_epoch) or
209
+ raise Melos::StateError.new("Welcome references an unknown resumption PSK (epoch #{psk_id.psk_epoch})")
210
+ else
211
+ raise Melos::ProtocolError.new("unknown PSK type #{psk_id.psktype}")
212
+ end
213
+ [psk_id.raw, value]
214
+ end
215
+ psk_secret = Melos::PSK.psk_secret(suite, psks)
216
+
217
+ # Decrypt the GroupInfo
218
+ welcome_key, welcome_nonce = Melos::EpochSecrets.welcome_key_and_nonce(suite, group_secrets.joiner_secret, psk_secret)
219
+ group_info = Melos::Struct::GroupInfo.new(
220
+ Melos::Crypto.aead_decrypt(suite, welcome_key, welcome_nonce, "", welcome.encrypted_group_info)
221
+ )
222
+ group_context = group_info.group_context
223
+ tree = verified_group_info_tree(suite, group_info, ratchet_tree)
224
+
225
+ # Find our own leaf: the one identical to our KeyPackage's LeafNode
226
+ leaf_index = tree.find_leaf_index { _1.raw == key_package.leaf_node.raw }
227
+ raise Melos::ProtocolError.new('our KeyPackage is not in the tree') if leaf_index.nil?
228
+ private_tree = Melos::PrivateTree.new
229
+ private_tree[leaf_index * 2] = encryption_private_key
230
+ # 12.4.3.1: a path secret in GroupSecrets is that of the common ancestor of our leaf and the signer's
231
+ if group_secrets.path_secret
232
+ common_ancestor = Melos::Tree.common_ancestor_semantic(leaf_index * 2, group_info.signer * 2, tree.n_leaves)
233
+ private_tree.set_path_secret(tree, common_ancestor, group_secrets.path_secret.path_secret)
234
+ end
235
+
236
+ # Enter the epoch's key schedule and check the GroupInfo's confirmation tag against it
237
+ epoch_secrets = Melos::EpochSecrets.from_joiner(suite, group_secrets.joiner_secret, psk_secret, group_context, n_leaves: tree.n_leaves,
238
+ secret_tree_options: secret_tree_options)
239
+ expected_tag = Melos::Crypto.mac(suite, epoch_secrets.confirmation_key, group_context.confirmed_transcript_hash)
240
+ raise Melos::ProtocolError.new('GroupInfo confirmation tag does not verify') unless group_info.confirmation_tag == expected_tag
241
+
242
+ group = new(
243
+ suite: suite, group_id: group_context.group_id, epoch: group_context.epoch, leaf_index: leaf_index,
244
+ signature_private_key: signature_private_key, ratchet_tree: tree, private_tree: private_tree,
245
+ extensions: group_context.extensions, confirmed_transcript_hash: group_context.confirmed_transcript_hash,
246
+ interim_transcript_hash: interim_transcript_hash(suite, group_context.confirmed_transcript_hash, group_info.confirmation_tag),
247
+ epoch_secrets: epoch_secrets, external_psks: external_psks, resumption_psk_lookup: resumption_psk_lookup,
248
+ member_matcher: member_matcher, confirmation_tag: group_info.confirmation_tag, **options
249
+ )
250
+ group.send(:validate_joined_state!)
251
+ unless resumed_psk_ids.empty?
252
+ group.send(:validate_resumption!, resumed_psk_ids.first, resumed_group_lookup&.call(resumed_psk_ids.first.psk_group_id), member_matcher)
253
+ end
254
+ epoch_secrets.discard_consumed! # 9.2: the joiner secret has done its work
255
+ group
256
+ end
257
+
258
+ # 12.4.3.1, 12.4.3.2: check a GroupInfo's version, suite and extensions, find its ratchet tree (given, or in the
259
+ # ratchet_tree extension), check the tree hash and the signature by the signer's leaf. Returns the tree.
260
+ def self.verified_group_info_tree(suite, group_info, ratchet_tree)
261
+ group_context = group_info.group_context
262
+ raise Melos::ProtocolError.new("unsupported MLS version #{group_context.version} in GroupContext") unless group_context.version == Melos::Constants::Version::MLS10
263
+ raise Melos::ProtocolError.new('GroupInfo is for a different cipher suite') unless group_context.cipher_suite == suite.suite_id
264
+ Melos::Struct::Extension.check_unique_types!(group_context.extensions, 'GroupContext extensions')
265
+ Melos::Struct::Extension.check_unique_types!(group_info.extensions, 'GroupInfo extensions')
266
+
267
+ # The ratchet tree: delivered out of band, or in the GroupInfo's ratchet_tree extension
268
+ ratchet_tree_data = ratchet_tree || group_info.extensions.find { _1.extension_type == Melos::Constants::ExtensionType::RATCHET_TREE }&.extension_data
269
+ raise ArgumentError.new('no ratchet tree available') if ratchet_tree_data.nil?
270
+ tree = Melos::RatchetTree.parse(suite, ratchet_tree_data)
271
+ raise Melos::ProtocolError.new('tree hash does not match GroupContext') unless tree.root_tree_hash == group_context.tree_hash
272
+
273
+ # Verify the GroupInfo signature with the signer's leaf
274
+ signer_leaf_node = tree.leaf_node_at(group_info.signer)
275
+ raise Melos::ProtocolError.new('GroupInfo signer is not in the tree') if signer_leaf_node.nil?
276
+ raise Melos::ProtocolError.new('GroupInfo signature does not verify') unless group_info.verify(suite, signer_leaf_node.signature_key)
277
+ tree
278
+ end
279
+
280
+ # 12.4.3.2: join a group by external commit, from a GroupInfo (or the MLSMessage carrying it) that has an
281
+ # external_pub extension. The joiner's leaf takes the credential, capabilities and extensions of leaf_node
282
+ # (a KeyPackage's leaf, say); the commit's path gives it fresh keys.
283
+ # remove: the leaf index of an earlier appearance of this member to replace (a "resync" commit)
284
+ # psk_ids: ids of external PSKs (in external_psks) to inject
285
+ # Returns [group, CommitResult]: send result.commit, and call group.merge_commit(result.staged) once the
286
+ # Delivery Service has accepted it. Until then the group is only a view of the epoch being joined.
287
+ def self.join_by_external_commit(suite, group_info, signature_private_key:, leaf_node:, ratchet_tree: nil, remove: nil, psk_ids: [],
288
+ external_psks: {}, authenticated_data: '', **options)
289
+ if group_info.is_a?(Melos::Struct::MLSMessage)
290
+ check_message_version!(group_info)
291
+ group_info = group_info.group_info
292
+ end
293
+ raise ArgumentError.new('not a GroupInfo') if group_info.nil?
294
+ secret_tree_options = options.slice(*SECRET_TREE_OPTIONS)
295
+ options = options.except(*SECRET_TREE_OPTIONS)
296
+ tree = verified_group_info_tree(suite, group_info, ratchet_tree)
297
+ external_pub = group_info.extensions.find { _1.extension_type == Melos::Constants::ExtensionType::EXTERNAL_PUB }
298
+ raise Melos::ProtocolError.new('GroupInfo has no external_pub extension') if external_pub.nil?
299
+ kem_output, init_secret = Melos::Crypto.external_init_sender(suite, Melos::Struct::ExternalPub.new(external_pub.extension_data).external_pub)
300
+
301
+ group_context = group_info.group_context
302
+ # 8.3: the epoch being joined is known only by the init secret the joiner sends to it
303
+ group = new(
304
+ suite: suite, group_id: group_context.group_id, epoch: group_context.epoch, leaf_index: nil,
305
+ signature_private_key: signature_private_key, ratchet_tree: tree, private_tree: Melos::PrivateTree.new,
306
+ extensions: group_context.extensions, confirmed_transcript_hash: group_context.confirmed_transcript_hash,
307
+ interim_transcript_hash: interim_transcript_hash(suite, group_context.confirmed_transcript_hash, group_info.confirmation_tag),
308
+ epoch_secrets: Melos::EpochSecrets.from_init_secret(suite, init_secret, secret_tree_options: secret_tree_options),
309
+ external_psks: external_psks, confirmation_tag: group_info.confirmation_tag, **options
310
+ )
311
+ group.instance_variable_set(:@external_joiner, true)
312
+ group.send(:validate_tree!, tree, group_context.extensions)
313
+ group.send(:validate_external_senders!, group_context.extensions)
314
+ [group, group.send(:create_external_commit, kem_output, leaf_node, remove: remove, psk_ids: psk_ids, authenticated_data: authenticated_data)]
315
+ end
316
+
317
+ # 8.4: a resumption PSK's usage must be one of the defined values
318
+ def self.check_resumption_usage!(psk_id)
319
+ return if [Melos::Constants::ResumptionPSKUsage::APPLICATION, Melos::Constants::ResumptionPSKUsage::REINIT,
320
+ Melos::Constants::ResumptionPSKUsage::BRANCH].include?(psk_id.usage)
321
+ raise Melos::ProtocolError.new("unknown resumption PSK usage #{psk_id.usage}")
322
+ end
323
+
324
+ # 8.2: interim_transcript_hash = Hash(confirmed_transcript_hash || InterimTranscriptHashInput)
325
+ def self.interim_transcript_hash(suite, confirmed_transcript_hash, confirmation_tag)
326
+ Melos::Crypto.hash(suite, confirmed_transcript_hash + Melos::Vec.string_to_vec(confirmation_tag))
327
+ end
328
+
329
+ # 8.1: the GroupContext of the current epoch
330
+ def group_context
331
+ @group_context ||= Melos::Struct::GroupContext.create(
332
+ cipher_suite: @suite.suite_id, group_id: @group_id, epoch: @epoch,
333
+ tree_hash: @ratchet_tree.root_tree_hash, confirmed_transcript_hash: @confirmed_transcript_hash, extensions: @extensions
334
+ )
335
+ end
336
+
337
+ def epoch_authenticator
338
+ @epoch_secrets.epoch_authenticator
339
+ end
340
+
341
+ # 8.5: a secret derived from this epoch for the application's own use; every member gets the same value
342
+ def export_secret(label, context, length)
343
+ @epoch_secrets.export(label, context, length)
344
+ end
345
+
346
+ ## Persistence
347
+
348
+ # version of the Hash produced by #to_h
349
+ STATE_FORMAT = 1
350
+
351
+ # The whole state of this member's view of the group, as a Hash whose keys are Symbols and whose values are
352
+ # binary Strings, Integers, true/false/nil, Arrays and such Hashes: secrets, private keys and ratchet
353
+ # positions included, so a restored group never reuses a nonce (6.3.1). Store it encrypted; that is
354
+ # the application's job. Melos::Persistence turns it into JSON.
355
+ # The credential_validator and external_proposal_validator procs are not included: pass them to .from_h again.
356
+ # include_external_psks: false when the PSKs are kept elsewhere (Melos::Client does)
357
+ def to_h(include_external_psks: true)
358
+ {
359
+ format: STATE_FORMAT,
360
+ cipher_suite: @suite.suite_id, group_id: @group_id, epoch: @epoch, leaf_index: @leaf_index,
361
+ signature_private_key: @signature_private_key,
362
+ ratchet_tree: @ratchet_tree.raw, private_tree: @private_tree.to_a,
363
+ extensions: @extensions.map(&:raw),
364
+ confirmed_transcript_hash: @confirmed_transcript_hash, interim_transcript_hash: @interim_transcript_hash,
365
+ epoch_secrets: @epoch_secrets.to_h,
366
+ resumption_psks: @resumption_psks.to_a,
367
+ external_psks: include_external_psks ? @external_psks.to_a : nil,
368
+ pending_proposals: @pending_proposals.map { |ref, authenticated_content| [ref, authenticated_content.raw] },
369
+ pending_updates: @pending_updates.to_a,
370
+ past_epochs: @past_epochs.map do |epoch, past|
371
+ [epoch, { epoch_secrets: past.epoch_secrets.to_h, group_context: past.group_context.raw, ratchet_tree: past.ratchet_tree.raw }]
372
+ end,
373
+ active: @active, pending_reinit: @pending_reinit&.raw, confirmation_tag: @confirmation_tag,
374
+ max_leaf_node_lifetime: @max_leaf_node_lifetime, max_past_epochs: @max_past_epochs, max_resumption_psks: @max_resumption_psks
375
+ }
376
+ end
377
+
378
+ # A group from #to_h.
379
+ # external_psks: the Hash to share with the restored group (a Client passes its own); defaults to the saved ones
380
+ # options: credential_validator:, external_proposal_validator:, resumption_psk_lookup:, member_matcher:, as for .create
381
+ def self.from_h(hash, external_psks: nil, **options)
382
+ raise ArgumentError.new("unknown group state format #{hash[:format]}") unless hash[:format] == STATE_FORMAT
383
+ suite = Melos::Crypto::CipherSuite.new(hash[:cipher_suite])
384
+ group = new(
385
+ suite: suite, group_id: hash[:group_id], epoch: hash[:epoch], leaf_index: hash[:leaf_index],
386
+ signature_private_key: hash[:signature_private_key],
387
+ ratchet_tree: Melos::RatchetTree.parse(suite, hash[:ratchet_tree]), private_tree: Melos::PrivateTree.from_a(hash[:private_tree]),
388
+ extensions: hash[:extensions].map { Melos::Struct::Extension.new(_1) },
389
+ confirmed_transcript_hash: hash[:confirmed_transcript_hash], interim_transcript_hash: hash[:interim_transcript_hash],
390
+ epoch_secrets: Melos::EpochSecrets.from_h(suite, hash[:epoch_secrets]),
391
+ external_psks: external_psks || (hash[:external_psks] || []).to_h,
392
+ max_leaf_node_lifetime: hash[:max_leaf_node_lifetime], max_past_epochs: hash[:max_past_epochs],
393
+ max_resumption_psks: hash[:max_resumption_psks], confirmation_tag: hash[:confirmation_tag], **options
394
+ )
395
+ group.send(:restore_state, hash)
396
+ group
397
+ end
398
+
399
+ # 12.4.3, 12.4.3.2: a signed GroupInfo for the current epoch, as an MLSMessage. With external_pub, it carries
400
+ # the epoch's external public key (8.3) so that a new member can join by external commit; with
401
+ # include_ratchet_tree, the tree (12.4.3.3).
402
+ def group_info(external_pub: true, include_ratchet_tree: true)
403
+ ensure_active!
404
+ raise Melos::StateError.new('the confirmation tag of this epoch is not known') if @confirmation_tag.nil?
405
+ extensions = []
406
+ if external_pub
407
+ _private, public_key = Melos::Crypto.external_key_pair(@suite, @epoch_secrets.external_secret)
408
+ extensions << Melos::Struct::Extension.create(extension_type: Melos::Constants::ExtensionType::EXTERNAL_PUB,
409
+ extension_data: Melos::Struct::ExternalPub.create(external_pub: public_key).raw)
410
+ end
411
+ extensions << Melos::Struct::Extension.create(extension_type: Melos::Constants::ExtensionType::RATCHET_TREE, extension_data: @ratchet_tree.raw) if include_ratchet_tree
412
+ info = Melos::Struct::GroupInfo.create(group_context: group_context, extensions: extensions, confirmation_tag: @confirmation_tag, signer: @leaf_index, signature: nil)
413
+ info.sign(@suite, @signature_private_key)
414
+ Melos::Struct::MLSMessage.create(group_info: info)
415
+ end
416
+
417
+ ## Receiving messages (6, 12.4)
418
+
419
+ # Unprotect an MLSMessage sent in this group and verify its signature. Handshake messages must be
420
+ # from the current epoch; application messages may also come from one of the last max_past_epochs
421
+ # epochs (9.1, 15.3), and are then checked against that epoch's secrets, tree and GroupContext.
422
+ # Returns the Melos::Struct::AuthenticatedContent.
423
+ def unprotect(mls_message)
424
+ self.class.check_message_version!(mls_message)
425
+ epoch_secrets, context, tree = @epoch_secrets, group_context, @ratchet_tree
426
+ authenticated_content =
427
+ case mls_message.wire_format
428
+ when Melos::Constants::WireFormat::MLS_PUBLIC_MESSAGE
429
+ mls_message.public_message.unprotect(@suite, @epoch_secrets.membership_key, group_context) or
430
+ raise Melos::ProtocolError.new('membership tag does not verify')
431
+ when Melos::Constants::WireFormat::MLS_PRIVATE_MESSAGE
432
+ private_message = mls_message.private_message
433
+ raise Melos::ProtocolError.new('message is for a different group') unless private_message.group_id == @group_id
434
+ if private_message.epoch != @epoch
435
+ past = @past_epochs[private_message.epoch] if private_message.content_type == Melos::Constants::ContentType::APPLICATION
436
+ raise Melos::ProtocolError.new("message is for epoch #{private_message.epoch}, current epoch is #{@epoch}") if past.nil?
437
+ epoch_secrets, context, tree = past.epoch_secrets, past.group_context, past.ratchet_tree
438
+ end
439
+ private_message.unprotect(@suite, epoch_secrets.secret_tree, epoch_secrets.sender_data_secret)
440
+ else
441
+ raise ArgumentError.new('not a PublicMessage or PrivateMessage')
442
+ end
443
+ content = authenticated_content.content
444
+ raise Melos::ProtocolError.new('message is for a different group') unless content.group_id == @group_id
445
+ raise Melos::ProtocolError.new("message is for epoch #{content.epoch}, current epoch is #{@epoch}") unless content.epoch == context.epoch
446
+ validate_non_member_content!(authenticated_content) unless content.sender.sender_type == Melos::Constants::SenderType::MEMBER
447
+ raise Melos::ProtocolError.new('signature does not verify') unless authenticated_content.verify(@suite, sender_signature_key(content, tree), context)
448
+ authenticated_content
449
+ end
450
+
451
+ # 12.1.8.1: the senders the external_senders GroupContext extension allows, as Melos::Struct::ExternalSender (empty without it)
452
+ def external_senders(extensions = @extensions)
453
+ extension = extensions.find { _1.extension_type == Melos::Constants::ExtensionType::EXTERNAL_SENDERS }
454
+ extension ? Melos::Struct::ExternalSenders.new(extension.extension_data).external_senders : []
455
+ end
456
+
457
+ # the earlier epochs whose application messages are still accepted, oldest first
458
+ def past_epochs
459
+ @past_epochs.keys
460
+ end
461
+
462
+ # Unprotect a message and act on it: cache a proposal, apply a commit, hand back application data.
463
+ # Returns the Melos::Struct::AuthenticatedContent in every case. A removed member cannot use this;
464
+ # it may still call #unprotect for late messages of the last epoch it was in.
465
+ def process_message(mls_message)
466
+ ensure_active!
467
+ authenticated_content = unprotect(mls_message)
468
+ case authenticated_content.content.content_type
469
+ when Melos::Constants::ContentType::PROPOSAL
470
+ process_proposal(authenticated_content)
471
+ when Melos::Constants::ContentType::COMMIT
472
+ process_commit(authenticated_content)
473
+ end
474
+ authenticated_content
475
+ end
476
+
477
+ # 12.4: remember a proposal of this epoch so a Commit can reference it
478
+ def process_proposal(authenticated_content)
479
+ ensure_active!
480
+ raise ArgumentError.new('not a proposal') unless authenticated_content.content.content_type == Melos::Constants::ContentType::PROPOSAL
481
+ @pending_proposals[Melos::Crypto.make_proposal_ref(@suite, authenticated_content.raw)] = authenticated_content
482
+ end
483
+
484
+ def process_commit(authenticated_content)
485
+ merge_commit(stage_commit(authenticated_content))
486
+ end
487
+
488
+ # 12.4.2: compute the next epoch's state from a received Commit without changing this group yet
489
+ def stage_commit(authenticated_content)
490
+ stage(authenticated_content, own_path: nil)
491
+ end
492
+
493
+ # 12.4.2: make a staged commit the current state; the group moves to the next epoch.
494
+ # If the commit removed this member, the group becomes inactive instead: it keeps the secrets of
495
+ # the last epoch it was in so late messages can still be read, but nothing more can be sent or processed.
496
+ def merge_commit(staged)
497
+ if staged.removes_us
498
+ @active = false
499
+ @pending_proposals = {}
500
+ return self
501
+ end
502
+ retain_past_epoch! unless @external_joiner
503
+ @external_joiner = false
504
+ @confirmation_tag = staged.confirmation_tag
505
+ @ratchet_tree = staged.ratchet_tree
506
+ @private_tree = staged.private_tree
507
+ @extensions = staged.extensions
508
+ @confirmed_transcript_hash = staged.confirmed_transcript_hash
509
+ @interim_transcript_hash = staged.interim_transcript_hash
510
+ @epoch_secrets = staged.epoch_secrets
511
+ @epoch += 1
512
+ # 9.2, 7.5: the previous epoch's secrets go with the previous EpochSecrets; the new epoch keeps only
513
+ # what it still needs, and the private tree keeps only keys for nodes that still carry them
514
+ @epoch_secrets.discard_consumed!
515
+ @private_tree.prune!(@ratchet_tree)
516
+ staged.path_secrets = nil
517
+ @group_context = nil
518
+ @pending_proposals = {}
519
+ @pending_updates = {}
520
+ @resumption_psks[@epoch] = @epoch_secrets.resumption_psk
521
+ @resumption_psks.delete_if { |epoch, _| epoch <= @epoch - @max_resumption_psks } # 8.6
522
+ # 12.4.2: after a ReInit the group is not used any more; the members wait for the new group's Welcome
523
+ if staged.reinit
524
+ @pending_reinit = staged.reinit
525
+ @active = false
526
+ end
527
+ self
528
+ end
529
+
530
+ ## Sending messages (6)
531
+
532
+ # Frame, sign and protect content for the wire in the current epoch. Returns a Melos::Struct::MLSMessage.
533
+ # content_type: Melos::Constants::ContentType; content: application data (String), Proposal or Commit
534
+ def protect(content_type, content, wire_format: Melos::Constants::WireFormat::MLS_PRIVATE_MESSAGE, authenticated_data: '', padding_size: 0)
535
+ ensure_active!
536
+ protect_authenticated_content(frame_and_sign(content_type, content, wire_format: wire_format, authenticated_data: authenticated_data), padding_size: padding_size)
537
+ end
538
+
539
+ # 6.1: application data is always sent as a PrivateMessage.
540
+ # 12.4: a member that has seen proposals in this epoch MUST commit them before sending application data.
541
+ def create_application_message(data, authenticated_data: '', padding_size: 0)
542
+ raise Melos::StateError.new('proposals are pending in this epoch; commit them before sending application data') unless @pending_proposals.empty?
543
+ protect(Melos::Constants::ContentType::APPLICATION, data,
544
+ wire_format: Melos::Constants::WireFormat::MLS_PRIVATE_MESSAGE, authenticated_data: authenticated_data, padding_size: padding_size)
545
+ end
546
+
547
+ # 12.1: send a Proposal; it is also remembered here so that our own Commit can reference it
548
+ def create_proposal(proposal, wire_format: Melos::Constants::WireFormat::MLS_PUBLIC_MESSAGE, authenticated_data: '', padding_size: 0)
549
+ authenticated_content = frame_and_sign(Melos::Constants::ContentType::PROPOSAL, proposal, wire_format: wire_format, authenticated_data: authenticated_data)
550
+ process_proposal(authenticated_content)
551
+ protect_authenticated_content(authenticated_content, padding_size: padding_size)
552
+ end
553
+
554
+ # 12.1.1: key_package is the new member's KeyPackage, or the MLSMessage carrying it
555
+ def create_add_proposal(key_package, **options)
556
+ if key_package.is_a?(Melos::Struct::MLSMessage)
557
+ self.class.check_message_version!(key_package)
558
+ # 10: a KeyPackage carried in an MLSMessage MUST have the same version as the message
559
+ raise Melos::ProtocolError.new('KeyPackage version differs from its MLSMessage') unless key_package.key_package.version == key_package.version
560
+ key_package = key_package.key_package
561
+ end
562
+ validate_key_package!(key_package, tree: @ratchet_tree, leaf_index: nil, extensions: @extensions, sending: true)
563
+ add = Melos::Struct::Add.create(key_package: key_package)
564
+ create_proposal(Melos::Struct::Proposal.create(proposal_type: Melos::Constants::ProposalType::ADD, add: add), **options)
565
+ end
566
+
567
+ # 12.1.2: propose replacing our leaf with one carrying a fresh encryption key, and optionally new
568
+ # capabilities or extensions. The new private key is kept until a commit applies the Update; it
569
+ # takes effect in #merge_commit. Our own commit never references our Update (12.2): its UpdatePath
570
+ # replaces the leaf anyway.
571
+ def create_update_proposal(capabilities: nil, extensions: nil, **options)
572
+ ensure_active!
573
+ current = @ratchet_tree.leaf_node_at(@leaf_index)
574
+ key_pair = Melos::Crypto.generate_encapsulation_key_pair(@suite)
575
+ leaf_node = Melos::Struct::LeafNode.create(
576
+ encryption_key: Melos::Crypto.serialize_public_key(@suite, key_pair),
577
+ signature_key: current.signature_key,
578
+ credential: current.credential,
579
+ capabilities: capabilities || current.capabilities,
580
+ leaf_node_source: Melos::Constants::LeafNodeSource::UPDATE,
581
+ lifetime: nil,
582
+ parent_hash: nil,
583
+ extensions: extensions || current.extensions,
584
+ signature: nil
585
+ )
586
+ leaf_node.sign(@suite, @signature_private_key, @group_id, @leaf_index)
587
+ validate_leaf_node!(leaf_node, context: :update, leaf_index: @leaf_index, tree: @ratchet_tree, extensions: @extensions, replacing: current, sending: true)
588
+ @pending_updates[leaf_node.encryption_key] = Melos::Crypto.serialize_private_key(@suite, key_pair)
589
+ update = Melos::Struct::Update.create(leaf_node: leaf_node)
590
+ create_proposal(Melos::Struct::Proposal.create(proposal_type: Melos::Constants::ProposalType::UPDATE, update: update), **options)
591
+ end
592
+
593
+ # 12.1.3
594
+ def create_remove_proposal(removed_leaf_index, **options)
595
+ raise ArgumentError.new("leaf #{removed_leaf_index} is blank") if @ratchet_tree.leaf_node_at(removed_leaf_index).nil?
596
+ remove = Melos::Struct::Remove.create(removed: removed_leaf_index)
597
+ create_proposal(Melos::Struct::Proposal.create(proposal_type: Melos::Constants::ProposalType::REMOVE, remove: remove), **options)
598
+ end
599
+
600
+ # 12.1.4 / 8.4: inject the external PSK psk_id, which every member must know, into the next epoch
601
+ def create_psk_proposal(psk_id, **options)
602
+ raise ArgumentError.new('unknown external PSK') unless @external_psks.key?(psk_id)
603
+ psk = Melos::Struct::PreSharedKey.create(
604
+ psk: Melos::Struct::PreSharedKeyID.create_external(psk_id: psk_id, psk_nonce: SecureRandom.random_bytes(@suite.kdf.n_h))
605
+ )
606
+ create_proposal(Melos::Struct::Proposal.create(proposal_type: Melos::Constants::ProposalType::PSK, psk: psk), **options)
607
+ end
608
+
609
+ # 8.6, 12.1.4: inject the resumption_psk of an earlier epoch of this group (or, with group_id:, of another
610
+ # group whose PSKs this member can look up) with usage application
611
+ def create_resumption_psk_proposal(epoch, group_id: @group_id, **options)
612
+ raise ArgumentError.new("no resumption PSK for epoch #{epoch}") if resumption_psk(group_id, epoch).nil?
613
+ psk_id = Melos::Struct::PreSharedKeyID.create_resumption(
614
+ usage: Melos::Constants::ResumptionPSKUsage::APPLICATION, psk_group_id: group_id, psk_epoch: epoch, psk_nonce: SecureRandom.random_bytes(@suite.kdf.n_h)
615
+ )
616
+ create_proposal(Melos::Struct::Proposal.create(proposal_type: Melos::Constants::ProposalType::PSK, psk: Melos::Struct::PreSharedKey.create(psk: psk_id)), **options)
617
+ end
618
+
619
+ # 12.1.5: propose reinitializing the group with new parameters (by default the current ones, to restart
620
+ # it). Once a commit covering it is merged, the group is inactive and Melos::Client#reinit_group creates the successor.
621
+ def create_reinit_proposal(group_id: @group_id, cipher_suite: @suite.suite_id, extensions: @extensions, version: Melos::Constants::Version::MLS10, **options)
622
+ reinit = Melos::Struct::ReInit.create(group_id: group_id, version: version, cipher_suite: cipher_suite, extensions: extensions)
623
+ create_proposal(Melos::Struct::Proposal.create(proposal_type: Melos::Constants::ProposalType::REINIT, reinit: reinit), **options)
624
+ end
625
+
626
+ # 12.4: commit the proposals of this epoch (those sent or received, by reference, plus inline_proposals by value).
627
+ # Returns a CommitResult; call #merge_commit(result.staged) once the Delivery Service has accepted the commit,
628
+ # and send result.welcome to the new members if there are any.
629
+ # path: :always includes a fresh UpdatePath (post-compromise security for the committer);
630
+ # :if_required leaves it out when 12.4 allows, i.e. the list is non-empty and has no path-required proposal
631
+ def create_commit(inline_proposals: [], wire_format: Melos::Constants::WireFormat::MLS_PUBLIC_MESSAGE, authenticated_data: '',
632
+ padding_size: 0, include_ratchet_tree: true, path: :always)
633
+ ensure_active!
634
+ raise ArgumentError.new('path must be :always or :if_required') unless %i[always if_required].include?(path)
635
+ # 12.2: a commit must not include an Update from the committer, so ours are left out (the path replaces our leaf)
636
+ referenced = @pending_proposals.reject { |_ref, authenticated_content| own_update?(authenticated_content) }
637
+ # 12.2: a ReInit must be alone; with other proposals at hand, those are committed and the ReInit can be sent again later
638
+ reinit = ->(proposal) { proposal.proposal_type == Melos::Constants::ProposalType::REINIT }
639
+ others = referenced.values.map { _1.content.proposal } + inline_proposals
640
+ if others.any? { !reinit.(_1) } && others.any?(&reinit)
641
+ referenced = referenced.reject { |_ref, authenticated_content| reinit.(authenticated_content.content.proposal) }
642
+ end
643
+ proposal_or_refs =
644
+ referenced.keys.map { Melos::Struct::ProposalOrRef.create(type: Melos::Constants::ProposalOrRefType::REFERENCE, proposal: nil, reference: _1) } +
645
+ inline_proposals.map { Melos::Struct::ProposalOrRef.create(type: Melos::Constants::ProposalOrRefType::PROPOSAL, proposal: _1, reference: nil) }
646
+ proposals = resolve_proposals(proposal_or_refs, @leaf_index)
647
+ validate_proposal_list!(proposals, @leaf_index)
648
+
649
+ # 12.4.2: the UpdatePath is built on the tree after the proposals, and not encrypted to the leaves being added
650
+ tree = @ratchet_tree.dup
651
+ private_tree = @private_tree.dup
652
+ extensions, joiners, _psk_ids = apply_proposals(tree, proposals, sending: true)
653
+ if path == :always || path_required?(proposals)
654
+ provisional_group_context = Melos::Struct::GroupContext.create(
655
+ cipher_suite: @suite.suite_id, group_id: @group_id, epoch: @epoch + 1,
656
+ tree_hash: '', confirmed_transcript_hash: @confirmed_transcript_hash, extensions: extensions # tree_hash is filled in by create_update_path
657
+ )
658
+ update = tree.create_update_path(private_tree, @leaf_index, @signature_private_key, provisional_group_context, joiners.map { _1.leaf_index * 2 })
659
+ own_path = { private_tree: private_tree, commit_secret: update[:commit_secret], path_secrets: update[:path_secrets] }
660
+ else
661
+ # 12.4.1: no path, so the commit secret is all zeros and our keys stay as they are
662
+ update = { update_path: nil }
663
+ own_path = { private_tree: private_tree, commit_secret: Melos::Crypto::Util.zero_vector(@suite.kdf.n_h), path_secrets: nil }
664
+ end
665
+
666
+ commit = Melos::Struct::Commit.create(proposals: proposal_or_refs, path: update[:update_path])
667
+ authenticated_content = frame_and_sign(Melos::Constants::ContentType::COMMIT, commit, wire_format: wire_format, authenticated_data: authenticated_data)
668
+ staged = stage(authenticated_content, own_path: own_path)
669
+ authenticated_content.auth.confirmation_tag = staged.confirmation_tag
670
+
671
+ result = CommitResult.new(
672
+ commit: protect_authenticated_content(authenticated_content, padding_size: padding_size),
673
+ welcome: staged.joiners.empty? ? nil : create_welcome(staged, include_ratchet_tree: include_ratchet_tree),
674
+ staged: staged
675
+ )
676
+ staged.path_secrets = nil # 9.2: used for the Welcome, not needed again
677
+ result
678
+ end
679
+
680
+ # 12.4.3.1: the Welcome for the members a staged commit adds
681
+ def create_welcome(staged, include_ratchet_tree: true)
682
+ extensions = []
683
+ extensions << Melos::Struct::Extension.create(extension_type: Melos::Constants::ExtensionType::RATCHET_TREE, extension_data: staged.ratchet_tree.raw) if include_ratchet_tree
684
+ group_info = Melos::Struct::GroupInfo.create(
685
+ group_context: staged.group_context, extensions: extensions, confirmation_tag: staged.confirmation_tag, signer: @leaf_index, signature: nil
686
+ )
687
+ group_info.sign(@suite, @signature_private_key)
688
+ welcome_key, welcome_nonce = staged.epoch_secrets.welcome_key_and_nonce
689
+ encrypted_group_info = Melos::Crypto.aead_encrypt(@suite, welcome_key, welcome_nonce, "", group_info.raw)
690
+
691
+ secrets = staged.joiners.map do |joiner|
692
+ path_secret = nil
693
+ if staged.path_secrets
694
+ # the joiner gets the path secret of the node where its direct path meets ours
695
+ common_ancestor = Melos::Tree.common_ancestor_semantic(joiner.leaf_index * 2, @leaf_index * 2, staged.ratchet_tree.n_leaves)
696
+ path_secret = Melos::Struct::PathSecret.create(path_secret: staged.path_secrets.fetch(common_ancestor))
697
+ end
698
+ group_secrets = Melos::Struct::GroupSecrets.create(joiner_secret: staged.epoch_secrets.joiner_secret, path_secret: path_secret, psks: staged.psk_ids)
699
+ kem_output, ciphertext = Melos::Crypto.encrypt_with_label(@suite, joiner.key_package.init_key, "Welcome", encrypted_group_info, group_secrets.raw)
700
+ Melos::Struct::EncryptedGroupSecrets.create(
701
+ new_member: joiner.key_package.ref(@suite),
702
+ encrypted_group_secrets: Melos::Struct::HPKECipherText.create(kem_output: kem_output, ciphertext: ciphertext)
703
+ )
704
+ end
705
+ welcome = Melos::Struct::Welcome.create(cipher_suite: @suite.suite_id, secrets: secrets, encrypted_group_info: encrypted_group_info)
706
+ Melos::Struct::MLSMessage.create(welcome: welcome)
707
+ end
708
+
709
+ private
710
+
711
+ # 12.4.2: the next epoch's state from a Commit.
712
+ # own_path: when we are the committer, { private_tree:, commit_secret:, path_secrets: } from create_update_path;
713
+ # the confirmation tag is then computed rather than verified
714
+ def stage(authenticated_content, own_path:)
715
+ ensure_active!
716
+ content = authenticated_content.content
717
+ raise ArgumentError.new('not a commit') unless content.content_type == Melos::Constants::ContentType::COMMIT
718
+ raise Melos::ProtocolError.new("commit is for epoch #{content.epoch}, current epoch is #{@epoch}") unless content.epoch == @epoch
719
+ commit = content.commit
720
+ case content.sender.sender_type
721
+ when Melos::Constants::SenderType::MEMBER
722
+ external = false
723
+ committer = content.sender.leaf_index
724
+ raise ArgumentError.new('our own commit must be staged through create_commit') if committer == @leaf_index && own_path.nil?
725
+ when Melos::Constants::SenderType::NEW_MEMBER_COMMIT
726
+ # 12.4.3.2: an external commit has a path, no proposals by reference, and its committer's leaf is placed below
727
+ external = true
728
+ committer = nil
729
+ raise Melos::ProtocolError.new('an external commit must have a path') if commit.path.nil?
730
+ raise Melos::ProtocolError.new('an external commit must not reference proposals') if commit.proposals.any?(&:reference)
731
+ else
732
+ raise Melos::ProtocolError.new("a commit cannot come from sender type #{content.sender.sender_type}")
733
+ end
734
+ raise ArgumentError.new('our external commit must be staged through Group.join_by_external_commit') if @external_joiner && own_path.nil?
735
+
736
+ proposals = resolve_proposals(commit.proposals, committer)
737
+ external ? validate_external_proposal_list!(proposals) : validate_proposal_list!(proposals, committer)
738
+ raise Melos::ProtocolError.new('commit must have a path') if commit.path.nil? && path_required?(proposals)
739
+
740
+ tree = @ratchet_tree.dup
741
+ private_tree = own_path ? own_path[:private_tree] : @private_tree.dup
742
+ extensions, joiners, psk_ids = apply_proposals(tree, proposals, sending: !own_path.nil?, external: external)
743
+ if external
744
+ # the joiner takes the leftmost blank leaf, as an Add would (after the Remove of a resync, 12.3)
745
+ committer = tree.add_leaf_node(commit.path.leaf_node)
746
+ raise ArgumentError.new('the external commit was built for another leaf') if own_path && committer != @leaf_index
747
+ validate_resync!(proposals, commit.path.leaf_node)
748
+ end
749
+
750
+ # 12.4.2: a commit may remove us; we cannot follow it any further, since the path is not encrypted to us.
751
+ # Our leaf index may be non-blank afterwards if an Add in the same commit reused it, so look at the Removes themselves.
752
+ # (A joiner's own external commit never removes the joiner, even when a resync frees the leaf it then takes.)
753
+ removes_us = !@external_joiner &&
754
+ proposals.any? { |proposal, _sender| proposal.proposal_type == Melos::Constants::ProposalType::REMOVE && proposal.remove.removed == @leaf_index }
755
+ if removes_us
756
+ return StagedCommit.new(ratchet_tree: tree, extensions: extensions, joiners: joiners, psk_ids: psk_ids, removes_us: true)
757
+ end
758
+ # if this commit applied an Update of ours, the UpdatePath below is encrypted to our new leaf key
759
+ adopt_pending_update!(tree, private_tree)
760
+
761
+ if commit.path.nil?
762
+ commit_secret = Melos::Crypto::Util.zero_vector(@suite.kdf.n_h)
763
+ else
764
+ validate_update_path!(tree, commit.path, committer, joiners, extensions, new_leaf: external) unless own_path
765
+ tree.merge_update_path(committer, commit.path)
766
+ if own_path
767
+ commit_secret = own_path[:commit_secret]
768
+ else
769
+ # the UpdatePath is encrypted with the provisional GroupContext: new epoch and tree, old transcript hash
770
+ provisional_group_context = Melos::Struct::GroupContext.create(
771
+ cipher_suite: @suite.suite_id, group_id: @group_id, epoch: @epoch + 1,
772
+ tree_hash: tree.root_tree_hash, confirmed_transcript_hash: @confirmed_transcript_hash, extensions: extensions
773
+ )
774
+ path_secret = tree.decrypt_path_secret(private_tree, commit.path, committer, @leaf_index, provisional_group_context, joiners.map(&:leaf_index))
775
+ commit_secret = tree.calculate_commit_secret(commit.path, committer, @leaf_index, path_secret)
776
+ end
777
+ end
778
+
779
+ # 8.2: transcript hashes
780
+ confirmed_transcript_hash = Melos::Crypto.hash(@suite, @interim_transcript_hash + authenticated_content.confirmed_transcript_hash_input.raw)
781
+ new_group_context = Melos::Struct::GroupContext.create(
782
+ cipher_suite: @suite.suite_id, group_id: @group_id, epoch: @epoch + 1,
783
+ tree_hash: tree.root_tree_hash, confirmed_transcript_hash: confirmed_transcript_hash, extensions: extensions
784
+ )
785
+
786
+ # 8: the next epoch's key schedule, and the confirmation tag that goes with it
787
+ # 8.3: an external commit starts the new epoch from the init secret the joiner sent in its ExternalInit
788
+ base = @epoch_secrets
789
+ if external && !own_path
790
+ external_private_key, _public_key = Melos::Crypto.external_key_pair(@suite, @epoch_secrets.external_secret)
791
+ kem_output = proposals.find { |proposal, _sender| proposal.proposal_type == Melos::Constants::ProposalType::EXTERNAL_INIT }.first.external_init.kem_output
792
+ base = Melos::EpochSecrets.from_init_secret(@suite, Melos::Crypto.external_init_receiver(@suite, external_private_key, kem_output),
793
+ secret_tree_options: @epoch_secrets.secret_tree_options)
794
+ end
795
+ epoch_secrets = base.next(commit_secret, psk_secret_for(psk_ids), new_group_context, n_leaves: tree.n_leaves)
796
+ confirmation_tag = Melos::Crypto.mac(@suite, epoch_secrets.confirmation_key, confirmed_transcript_hash)
797
+ if own_path.nil? && authenticated_content.auth.confirmation_tag != confirmation_tag
798
+ raise Melos::ProtocolError.new('confirmation tag does not verify')
799
+ end
800
+
801
+ StagedCommit.new(
802
+ reinit: proposals.find { |proposal, _sender| proposal.proposal_type == Melos::Constants::ProposalType::REINIT }&.first&.reinit,
803
+ ratchet_tree: tree, private_tree: private_tree, extensions: extensions,
804
+ confirmed_transcript_hash: confirmed_transcript_hash,
805
+ interim_transcript_hash: self.class.interim_transcript_hash(@suite, confirmed_transcript_hash, confirmation_tag),
806
+ epoch_secrets: epoch_secrets, group_context: new_group_context, confirmation_tag: confirmation_tag,
807
+ joiners: joiners, path_secrets: own_path && own_path[:path_secrets], psk_ids: psk_ids
808
+ )
809
+ end
810
+
811
+ # 9.1, 15.3: as the group leaves the current epoch, keep what its late application messages need,
812
+ # and forget epochs older than max_past_epochs (9.2: their secrets are then deleted)
813
+ def retain_past_epoch!
814
+ if @max_past_epochs.positive?
815
+ @past_epochs[@epoch] = PastEpoch.new(
816
+ epoch_secrets: @epoch_secrets.retain_for_past_messages!, group_context: group_context, ratchet_tree: @ratchet_tree
817
+ )
818
+ end
819
+ @past_epochs.delete_if { |epoch, _| epoch <= @epoch - @max_past_epochs }
820
+ end
821
+
822
+ # the parts of #to_h that .new does not take
823
+ def restore_state(hash)
824
+ @resumption_psks = hash[:resumption_psks].to_h
825
+ @pending_proposals = hash[:pending_proposals].to_h { |ref, raw| [ref, Melos::Struct::AuthenticatedContent.new(raw)] }
826
+ @pending_updates = hash[:pending_updates].to_h
827
+ @past_epochs = hash[:past_epochs].to_h do |epoch, past|
828
+ [epoch, PastEpoch.new(
829
+ epoch_secrets: Melos::EpochSecrets.from_h(@suite, past[:epoch_secrets]),
830
+ group_context: Melos::Struct::GroupContext.new(past[:group_context]),
831
+ ratchet_tree: Melos::RatchetTree.parse(@suite, past[:ratchet_tree])
832
+ )]
833
+ end
834
+ @active = hash[:active]
835
+ @pending_reinit = hash[:pending_reinit] && Melos::Struct::ReInit.new(hash[:pending_reinit])
836
+ end
837
+
838
+ def ensure_active!
839
+ return if @active
840
+ raise Melos::StateError.new("the group was reinitialized in epoch #{@epoch}; join its successor") if @pending_reinit
841
+ raise Melos::StateError.new("this member was removed from the group in epoch #{@epoch}")
842
+ end
843
+
844
+ # an Update proposal sent by this member
845
+ def own_update?(authenticated_content)
846
+ content = authenticated_content.content
847
+ content.content_type == Melos::Constants::ContentType::PROPOSAL &&
848
+ content.proposal.proposal_type == Melos::Constants::ProposalType::UPDATE &&
849
+ content.sender.sender_type == Melos::Constants::SenderType::MEMBER && content.sender.leaf_index == @leaf_index
850
+ end
851
+
852
+ # 12.1.2: if our leaf in tree now carries the key of an Update we sent, install the private key we kept for it
853
+ def adopt_pending_update!(tree, private_tree)
854
+ private_key = @pending_updates[tree.leaf_node_at(@leaf_index)&.encryption_key]
855
+ private_tree[@leaf_index * 2] = private_key if private_key
856
+ end
857
+
858
+ # 12.4: a commit's path is required if its proposal list is empty or contains a path-required type
859
+ def path_required?(proposals)
860
+ proposals.empty? || proposals.any? do |proposal, _sender|
861
+ [Melos::Constants::ProposalType::UPDATE, Melos::Constants::ProposalType::REMOVE,
862
+ Melos::Constants::ProposalType::EXTERNAL_INIT, Melos::Constants::ProposalType::GROUP_CONTEXT_EXTENSIONS].include?(proposal.proposal_type)
863
+ end
864
+ end
865
+
866
+ # 6.1: the key that signed this FramedContent, by its sender type; members are looked up in tree
867
+ def sender_signature_key(content, tree = @ratchet_tree)
868
+ sender = content.sender
869
+ case sender.sender_type
870
+ when Melos::Constants::SenderType::MEMBER
871
+ leaf_node = tree.leaf_node_at(sender.leaf_index)
872
+ raise Melos::ProtocolError.new("sender leaf #{sender.leaf_index} is blank") if leaf_node.nil?
873
+ leaf_node.signature_key
874
+ when Melos::Constants::SenderType::EXTERNAL
875
+ # 12.1.8: only with the external_senders extension, by index into it
876
+ external_sender = external_senders[sender.sender_index]
877
+ raise Melos::ProtocolError.new("no external sender #{sender.sender_index} in the external_senders extension") if external_sender.nil?
878
+ external_sender.signature_key
879
+ when Melos::Constants::SenderType::NEW_MEMBER_PROPOSAL
880
+ # the joiner signs its own Add with the key of the KeyPackage's leaf
881
+ content.proposal.add.key_package.leaf_node.signature_key
882
+ when Melos::Constants::SenderType::NEW_MEMBER_COMMIT
883
+ # 12.4.3.2: an external commit is signed with the key of its path's leaf
884
+ leaf_node = content.commit.path&.leaf_node
885
+ raise Melos::ProtocolError.new('an external commit must have a path') if leaf_node.nil?
886
+ leaf_node.signature_key
887
+ else
888
+ raise Melos::ProtocolError.new("unknown sender type #{sender.sender_type}")
889
+ end
890
+ end
891
+
892
+ # 6.1, 12.1.8: a message from outside the group is a PublicMessage carrying a proposal of an allowed
893
+ # type (only Add from a new member), and must be authorized by the application
894
+ def validate_non_member_content!(authenticated_content)
895
+ content = authenticated_content.content
896
+ case content.sender.sender_type
897
+ when Melos::Constants::SenderType::EXTERNAL, Melos::Constants::SenderType::NEW_MEMBER_PROPOSAL
898
+ raise Melos::ProtocolError.new('a proposal from outside the group must be a PublicMessage') unless authenticated_content.wire_format == Melos::Constants::WireFormat::MLS_PUBLIC_MESSAGE
899
+ raise Melos::ProtocolError.new('a message from outside the group must be a proposal') unless content.content_type == Melos::Constants::ContentType::PROPOSAL
900
+ allowed = content.sender.sender_type == Melos::Constants::SenderType::EXTERNAL ? EXTERNAL_PROPOSAL_TYPES : [Melos::Constants::ProposalType::ADD]
901
+ proposal_type = content.proposal.proposal_type
902
+ raise Melos::ProtocolError.new("proposal type #{proposal_type} cannot be sent from outside the group by this sender") unless allowed.include?(proposal_type)
903
+ raise Melos::ProtocolError.new('external proposal not authorized') unless @external_proposal_validator.call(authenticated_content)
904
+ when Melos::Constants::SenderType::NEW_MEMBER_COMMIT
905
+ raise Melos::ProtocolError.new('an external commit must be a PublicMessage') unless authenticated_content.wire_format == Melos::Constants::WireFormat::MLS_PUBLIC_MESSAGE
906
+ raise Melos::ProtocolError.new('a new_member_commit message must be a commit') unless content.content_type == Melos::Constants::ContentType::COMMIT
907
+ else
908
+ raise Melos::ProtocolError.new("unknown sender type #{content.sender.sender_type}")
909
+ end
910
+ end
911
+
912
+ # 12.4: the proposals a Commit covers, by value or by reference, as [proposal, sender leaf index] pairs;
913
+ # the sender is nil for a proposal from an external sender or a new member (12.1.8)
914
+ def resolve_proposals(proposal_or_refs, committer)
915
+ proposal_or_refs.map do |proposal_or_ref|
916
+ if proposal_or_ref.proposal
917
+ [proposal_or_ref.proposal, committer]
918
+ else
919
+ authenticated_content = @pending_proposals[proposal_or_ref.reference]
920
+ raise Melos::ProtocolError.new('commit references a proposal we have not received') if authenticated_content.nil?
921
+ sender = authenticated_content.content.sender
922
+ [authenticated_content.content.proposal, sender.sender_type == Melos::Constants::SenderType::MEMBER ? sender.leaf_index : nil]
923
+ end
924
+ end
925
+ end
926
+
927
+ # 12.3: apply proposals to tree, in the order GroupContextExtensions, Update, Remove, Add, PreSharedKey,
928
+ # validating each leaf node that goes in (7.3, 10.1) and the resulting membership (12.2).
929
+ # sending: we are the committer, so lifetimes are checked against the current time (7.3)
930
+ # Returns [extensions, joiners (Joiner for each added member), psk_ids]
931
+ # external: the list of an external commit, where ExternalInit belongs (12.2)
932
+ def apply_proposals(tree, proposals, sending:, external: false)
933
+ of_type = ->(type) { proposals.select { |proposal, _sender| proposal.proposal_type == type } }
934
+ types = proposals.map { |proposal, _sender| proposal.proposal_type }
935
+ # 12.2, 13.2: a proposal type not supported by every member makes the list invalid; we support only the RFC's own types
936
+ unknown = types - KNOWN_PROPOSAL_TYPES
937
+ raise Melos::UnsupportedError.new("unknown proposal types: #{unknown.map { '0x%04x' % _1 }.join(', ')}") unless unknown.empty?
938
+ raise Melos::ProtocolError.new('an ExternalInit proposal is only valid in an external commit') if !external && types.include?(Melos::Constants::ProposalType::EXTERNAL_INIT)
939
+ extensions = @extensions
940
+ of_type.(Melos::Constants::ProposalType::GROUP_CONTEXT_EXTENSIONS).each do |proposal, _sender|
941
+ Melos::Struct::Extension.check_unique_types!(proposal.group_context_extensions.extensions, 'GroupContextExtensions proposal')
942
+ extensions = proposal.group_context_extensions.extensions
943
+ end
944
+ of_type.(Melos::Constants::ProposalType::UPDATE).each do |proposal, sender|
945
+ validate_leaf_node!(proposal.update.leaf_node, context: :update, leaf_index: sender, tree: tree, extensions: extensions,
946
+ replacing: tree.leaf_node_at(sender), sending: sending)
947
+ tree.update_leaf_node(sender, proposal.update.leaf_node)
948
+ end
949
+ of_type.(Melos::Constants::ProposalType::REMOVE).each do |proposal, _sender|
950
+ # 12.1.3: removed MUST identify a non-blank leaf (this also rejects two Removes of the same leaf, 12.2)
951
+ raise Melos::ProtocolError.new("Remove proposal names a blank leaf (#{proposal.remove.removed})") if tree.leaf_node_at(proposal.remove.removed).nil?
952
+ tree.remove_leaf_node(proposal.remove.removed)
953
+ end
954
+ joiners = of_type.(Melos::Constants::ProposalType::ADD).map do |proposal, _sender|
955
+ key_package = proposal.add.key_package
956
+ # 10.1: the KeyPackage's version and cipher suite MUST match the group's
957
+ raise Melos::ProtocolError.new("Add proposal's KeyPackage has version #{key_package.version}") unless key_package.version == Melos::Constants::Version::MLS10
958
+ raise Melos::ProtocolError.new("Add proposal's KeyPackage is for cipher suite #{key_package.cipher_suite}") unless key_package.cipher_suite == @suite.suite_id
959
+ leaf_index = tree.add_leaf_node(key_package.leaf_node)
960
+ validate_key_package!(key_package, tree: tree, leaf_index: leaf_index, extensions: extensions, sending: sending)
961
+ Joiner.new(leaf_index, key_package)
962
+ end
963
+ psk_ids = of_type.(Melos::Constants::ProposalType::PSK).map { |proposal, _sender| proposal.psk.psk }
964
+ validate_external_senders!(extensions) if extensions != @extensions # 5.3.1, 12.1.8.1: when the extension is added or changed
965
+ # 12.2, 12.1.7: the members that remain must all be compatible with the new extensions and with each other
966
+ validate_members!(tree, extensions)
967
+ [extensions, joiners, psk_ids]
968
+ end
969
+
970
+ # 8.4: the PSK secret for the PreSharedKeyIDs of a commit
971
+ def psk_secret_for(psk_ids)
972
+ psks = psk_ids.map do |psk_id|
973
+ # 12.1.4: psk_nonce MUST be KDF.Nh bytes long
974
+ raise Melos::ProtocolError.new('psk_nonce has the wrong length') unless psk_id.psk_nonce.bytesize == @suite.kdf.n_h
975
+ value =
976
+ case psk_id.psktype
977
+ when Melos::Constants::PSKType::EXTERNAL
978
+ @external_psks.fetch(psk_id.psk_id) { raise Melos::StateError.new('commit references an unknown external PSK') }
979
+ when Melos::Constants::PSKType::RESUMPTION
980
+ self.class.check_resumption_usage!(psk_id)
981
+ if psk_id.reinit_or_branch?
982
+ # 11.2, 11.3, 12.1.4: only in the initial commit of a reinitialized or branched group, which no other member processes
983
+ raise Melos::ProtocolError.new('a PreSharedKey proposal must not use a reinit or branch resumption PSK') unless @resumption_override&.first == psk_id.raw
984
+ @resumption_override.last
985
+ else
986
+ resumption_psk(psk_id.psk_group_id, psk_id.psk_epoch) or
987
+ raise Melos::StateError.new("no resumption PSK for epoch #{psk_id.psk_epoch} of that group")
988
+ end
989
+ else
990
+ raise Melos::ProtocolError.new("unknown PSK type #{psk_id.psktype}")
991
+ end
992
+ [psk_id.raw, value]
993
+ end
994
+ Melos::PSK.psk_secret(@suite, psks)
995
+ end
996
+
997
+ # 8.6: the resumption_psk of an epoch of this group or, through resumption_psk_lookup, of another
998
+ def resumption_psk(group_id, epoch)
999
+ group_id == @group_id ? @resumption_psks[epoch] : @resumption_psk_lookup&.call(group_id, epoch)
1000
+ end
1001
+
1002
+ # 11.2, 11.3: the first commit of a group created to reinitialize or branch another: it adds key_packages
1003
+ # and carries the resumption PSK psk_id (whose value is psk) that ties the new group to the old one.
1004
+ # Only a group in epoch 0 with no other member can do this, since nobody else processes the commit.
1005
+ # Returns the CommitResult; the caller merges it right away.
1006
+ def create_resumption_commit(key_packages, psk_id, psk, **options)
1007
+ raise ArgumentError.new('a resumption commit is the first commit of a new group') unless @epoch.zero? && @ratchet_tree.n_leaves == 1
1008
+ raise ArgumentError.new('proposals are pending') unless @pending_proposals.empty?
1009
+ adds = key_packages.map do |key_package|
1010
+ key_package = key_package.key_package if key_package.is_a?(Melos::Struct::MLSMessage)
1011
+ validate_key_package!(key_package, tree: @ratchet_tree, leaf_index: nil, extensions: @extensions, sending: true)
1012
+ Melos::Struct::Proposal.create(proposal_type: Melos::Constants::ProposalType::ADD, add: Melos::Struct::Add.create(key_package: key_package))
1013
+ end
1014
+ psk_proposal = Melos::Struct::Proposal.create(proposal_type: Melos::Constants::ProposalType::PSK, psk: Melos::Struct::PreSharedKey.create(psk: psk_id))
1015
+ @resumption_override = [psk_id.raw, psk]
1016
+ create_commit(inline_proposals: adds + [psk_proposal], **options)
1017
+ ensure
1018
+ @resumption_override = nil
1019
+ end
1020
+
1021
+ # 12.4.3.2 (joiner): the external commit, from the view of the epoch built by .join_by_external_commit:
1022
+ # ExternalInit, the Remove of a resync, PSKs, all by value, and a path from the leftmost blank leaf
1023
+ def create_external_commit(kem_output, leaf_node, remove:, psk_ids:, authenticated_data:)
1024
+ proposals = [Melos::Struct::Proposal.create(proposal_type: Melos::Constants::ProposalType::EXTERNAL_INIT,
1025
+ external_init: Melos::Struct::ExternalInit.create(kem_output: kem_output))]
1026
+ proposals << Melos::Struct::Proposal.create(proposal_type: Melos::Constants::ProposalType::REMOVE, remove: Melos::Struct::Remove.create(removed: remove)) if remove
1027
+ psk_ids.each do |psk_id|
1028
+ raise ArgumentError.new('unknown external PSK') unless @external_psks.key?(psk_id)
1029
+ psk = Melos::Struct::PreSharedKeyID.create_external(psk_id: psk_id, psk_nonce: SecureRandom.random_bytes(@suite.kdf.n_h))
1030
+ proposals << Melos::Struct::Proposal.create(proposal_type: Melos::Constants::ProposalType::PSK, psk: Melos::Struct::PreSharedKey.create(psk: psk))
1031
+ end
1032
+ pairs = proposals.map { [_1, nil] }
1033
+ validate_external_proposal_list!(pairs)
1034
+
1035
+ tree = @ratchet_tree.dup
1036
+ private_tree = Melos::PrivateTree.new
1037
+ extensions, _joiners, _psk_ids = apply_proposals(tree, pairs, sending: true, external: true)
1038
+ @leaf_index = tree.add_leaf_node(leaf_node) # a template: the path replaces it with a leaf of source commit
1039
+ provisional_group_context = Melos::Struct::GroupContext.create(
1040
+ cipher_suite: @suite.suite_id, group_id: @group_id, epoch: @epoch + 1,
1041
+ tree_hash: '', confirmed_transcript_hash: @confirmed_transcript_hash, extensions: extensions
1042
+ )
1043
+ update = tree.create_update_path(private_tree, @leaf_index, @signature_private_key, provisional_group_context)
1044
+ validate_leaf_node!(update[:update_path].leaf_node, context: :commit, leaf_index: @leaf_index, tree: tree, extensions: extensions, sending: true)
1045
+
1046
+ commit = Melos::Struct::Commit.create(
1047
+ proposals: proposals.map { Melos::Struct::ProposalOrRef.create(type: Melos::Constants::ProposalOrRefType::PROPOSAL, proposal: _1, reference: nil) },
1048
+ path: update[:update_path]
1049
+ )
1050
+ authenticated_content = frame_and_sign(
1051
+ Melos::Constants::ContentType::COMMIT, commit, wire_format: Melos::Constants::WireFormat::MLS_PUBLIC_MESSAGE, authenticated_data: authenticated_data,
1052
+ sender: Melos::Struct::Sender.create_new_member(Melos::Constants::SenderType::NEW_MEMBER_COMMIT)
1053
+ )
1054
+ staged = stage(authenticated_content, own_path: { private_tree: private_tree, commit_secret: update[:commit_secret], path_secrets: nil })
1055
+ authenticated_content.auth.confirmation_tag = staged.confirmation_tag
1056
+ CommitResult.new(commit: protect_authenticated_content(authenticated_content, padding_size: 0), welcome: nil, staged: staged)
1057
+ end
1058
+
1059
+ # 6: FramedContent -> AuthenticatedContent, signed with our key in the current GroupContext
1060
+ def frame_and_sign(content_type, content, wire_format:, authenticated_data:, sender: Melos::Struct::Sender.create_member(@leaf_index))
1061
+ framed_content = Melos::Struct::FramedContent.create(
1062
+ group_id: @group_id, epoch: @epoch, sender: sender,
1063
+ authenticated_data: authenticated_data, content_type: content_type, content: content
1064
+ )
1065
+ authenticated_content = Melos::Struct::AuthenticatedContent.create(wire_format: wire_format, content: framed_content, auth: nil)
1066
+ authenticated_content.sign(@suite, @signature_private_key, group_context)
1067
+ authenticated_content
1068
+ end
1069
+
1070
+ # 6.2, 6.3: AuthenticatedContent -> PublicMessage or PrivateMessage, wrapped in an MLSMessage
1071
+ def protect_authenticated_content(authenticated_content, padding_size:)
1072
+ case authenticated_content.wire_format
1073
+ when Melos::Constants::WireFormat::MLS_PUBLIC_MESSAGE
1074
+ # 6.2: only a member's message carries a membership tag
1075
+ member = authenticated_content.content.sender.sender_type == Melos::Constants::SenderType::MEMBER
1076
+ message = Melos::Struct::PublicMessage.protect(authenticated_content, @suite, member ? @epoch_secrets.membership_key : nil, group_context)
1077
+ Melos::Struct::MLSMessage.create(public_message: message)
1078
+ when Melos::Constants::WireFormat::MLS_PRIVATE_MESSAGE
1079
+ message = Melos::Struct::PrivateMessage.protect(authenticated_content, @suite, @epoch_secrets.secret_tree, @epoch_secrets.sender_data_secret, padding_size)
1080
+ Melos::Struct::MLSMessage.create(private_message: message)
1081
+ else
1082
+ raise ArgumentError.new('wire format must be PublicMessage or PrivateMessage')
1083
+ end
1084
+ end
1085
+ end
1086
+
1087
+ require_relative 'group/validation'