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,166 @@
1
+ require_relative 'crypto'
2
+ require_relative 'secret_tree'
3
+
4
+ # The key schedule (RFC 9420 Section 8) for one epoch: the epoch_secret and the secrets
5
+ # derived from it (Table 4), the joiner and PSK secrets that produced it (needed to build
6
+ # a Welcome, 12.4.3.1), and the epoch's secret tree (Section 9).
7
+ #
8
+ # A new epoch comes from #next with the commit secret, PSK secret and new GroupContext,
9
+ # which uses this epoch's init_secret as Section 8 describes.
10
+ class Melos::EpochSecrets
11
+ attr_reader :suite, :epoch_secret, :joiner_secret, :psk_secret, :n_leaves, :secret_tree_options
12
+
13
+ # Table 4, plus init_secret which is derived the same way
14
+ DERIVED_SECRETS = {
15
+ sender_data_secret: 'sender data',
16
+ encryption_secret: 'encryption',
17
+ exporter_secret: 'exporter',
18
+ external_secret: 'external',
19
+ confirmation_key: 'confirm',
20
+ membership_key: 'membership',
21
+ resumption_psk: 'resumption',
22
+ epoch_authenticator: 'authentication',
23
+ init_secret: 'init'
24
+ }.freeze
25
+
26
+ DERIVED_SECRETS.each do |name, label|
27
+ define_method(name) do
28
+ @derived[name] ||= Melos::Crypto.derive_secret(@suite, require_epoch_secret(name), label)
29
+ end
30
+ end
31
+
32
+ # whether the derived secret name can be had: it is held, or epoch_secret is there to derive it
33
+ def available?(name)
34
+ @derived.key?(name) || !@epoch_secret.nil?
35
+ end
36
+
37
+ # derived: secrets known without an epoch_secret (see .from_init_secret and .from_components)
38
+ # secret_tree_options: passed to Melos::SecretTree (max_forward_distance:, out_of_order_tolerance:);
39
+ # every epoch made by #next inherits them
40
+ def initialize(suite, epoch_secret: nil, joiner_secret: nil, psk_secret: nil, n_leaves: nil, derived: {}, secret_tree_options: {})
41
+ unknown = derived.keys - DERIVED_SECRETS.keys
42
+ raise ArgumentError.new("unknown secrets: #{unknown.join(', ')}") unless unknown.empty?
43
+ @suite = suite
44
+ @epoch_secret = epoch_secret
45
+ @joiner_secret = joiner_secret
46
+ @psk_secret = psk_secret
47
+ @n_leaves = n_leaves
48
+ @derived = derived.dup
49
+ @secret_tree_options = secret_tree_options
50
+ end
51
+
52
+ def self.from_epoch_secret(suite, epoch_secret, n_leaves: nil)
53
+ new(suite, epoch_secret: epoch_secret, n_leaves: n_leaves)
54
+ end
55
+
56
+ # 8: epoch_secret = ExpandWithLabel(Extract(joiner_secret, psk_secret), "epoch", GroupContext)
57
+ # This is how a new member joins an epoch from a Welcome (12.4.3.1).
58
+ def self.from_joiner(suite, joiner_secret, psk_secret, group_context, n_leaves: nil, secret_tree_options: {})
59
+ member_secret = Melos::Crypto.kdf_extract(suite, joiner_secret, psk_secret)
60
+ epoch_secret = Melos::Crypto.expand_with_label(suite, member_secret, "epoch", group_context.raw, suite.kdf.n_h)
61
+ new(suite, epoch_secret: epoch_secret, joiner_secret: joiner_secret, psk_secret: psk_secret, n_leaves: n_leaves,
62
+ secret_tree_options: secret_tree_options)
63
+ end
64
+
65
+ # 8: the state before an epoch exists, when only init_secret is known (a fresh random
66
+ # value for a new group). Only #next is meaningful on it.
67
+ def self.from_init_secret(suite, init_secret, secret_tree_options: {})
68
+ new(suite, derived: { init_secret: init_secret }, secret_tree_options: secret_tree_options)
69
+ end
70
+
71
+ # an epoch given by some of its derived secrets rather than by epoch_secret; for test vectors
72
+ def self.from_components(suite, n_leaves: nil, **secrets)
73
+ new(suite, n_leaves: n_leaves, derived: secrets)
74
+ end
75
+
76
+ # 8: welcome_secret = DeriveSecret(Extract(joiner_secret, psk_secret), "welcome")
77
+ def self.welcome_secret(suite, joiner_secret, psk_secret)
78
+ Melos::Crypto.derive_secret(suite, Melos::Crypto.kdf_extract(suite, joiner_secret, psk_secret), "welcome")
79
+ end
80
+
81
+ # 12.4.3.1: the key and nonce that encrypt the GroupInfo in a Welcome
82
+ def self.welcome_key_and_nonce(suite, joiner_secret, psk_secret)
83
+ ws = welcome_secret(suite, joiner_secret, psk_secret)
84
+ [
85
+ Melos::Crypto.expand_with_label(suite, ws, "key", "", suite.hpke.n_k),
86
+ Melos::Crypto.expand_with_label(suite, ws, "nonce", "", suite.hpke.n_n)
87
+ ]
88
+ end
89
+
90
+ def welcome_secret
91
+ self.class.welcome_secret(@suite, require_joiner_secret(:welcome_secret), @psk_secret)
92
+ end
93
+
94
+ def welcome_key_and_nonce
95
+ self.class.welcome_key_and_nonce(@suite, require_joiner_secret(:welcome_key_and_nonce), @psk_secret)
96
+ end
97
+
98
+ # 8: the next epoch. joiner_secret = ExpandWithLabel(Extract(init_secret, commit_secret), "joiner", GroupContext)
99
+ # n_leaves: leaf count of the ratchet tree in the new epoch, for its secret tree
100
+ def next(commit_secret, psk_secret, group_context, n_leaves: @n_leaves)
101
+ joiner_secret = Melos::Crypto.expand_with_label(
102
+ @suite, Melos::Crypto.kdf_extract(@suite, init_secret, commit_secret), "joiner", group_context.raw, @suite.kdf.n_h
103
+ )
104
+ self.class.from_joiner(@suite, joiner_secret, psk_secret, group_context, n_leaves: n_leaves, secret_tree_options: @secret_tree_options)
105
+ end
106
+
107
+ # 8.5: MLS-Exporter(label, context, length) = ExpandWithLabel(DeriveSecret(exporter_secret, label), "exported", Hash(context), length)
108
+ def export(label, context, length)
109
+ Melos::Crypto.expand_with_label(@suite, Melos::Crypto.derive_secret(@suite, exporter_secret, label), "exported", Melos::Crypto.hash(@suite, context), length)
110
+ end
111
+
112
+ # 9.2: once this epoch is the current one, the secrets that produced it have been consumed. Derive
113
+ # everything the epoch still needs (the Table 4 secrets and the secret tree), then drop epoch_secret,
114
+ # joiner_secret, psk_secret and encryption_secret. init_secret stays until the next epoch exists.
115
+ # Ruby cannot zeroize strings; this drops the references so they can be collected.
116
+ def discard_consumed!
117
+ return self if @epoch_secret.nil?
118
+ DERIVED_SECRETS.each_key { send(_1) }
119
+ secret_tree
120
+ @derived.delete(:encryption_secret)
121
+ @epoch_secret = nil
122
+ @joiner_secret = nil
123
+ @psk_secret = nil
124
+ self
125
+ end
126
+
127
+ # 9.1, 15.3: what an epoch that is no longer current keeps so that its late application messages
128
+ # can still be read: the secret tree and the sender data secret. Everything else, init_secret
129
+ # included (consumed by the next epoch, 9.2), is dropped.
130
+ def retain_for_past_messages!
131
+ discard_consumed!
132
+ @derived.select! { |name, _| name == :sender_data_secret }
133
+ self
134
+ end
135
+
136
+ # the epoch's remaining secrets and its secret tree's state, as a Hash of binary strings and integers
137
+ def to_h
138
+ {
139
+ epoch_secret: @epoch_secret, joiner_secret: @joiner_secret, psk_secret: @psk_secret, n_leaves: @n_leaves,
140
+ derived: @derived.dup, secret_tree_options: @secret_tree_options, secret_tree: @secret_tree&.to_h
141
+ }
142
+ end
143
+
144
+ def self.from_h(suite, hash)
145
+ epoch_secrets = new(suite, epoch_secret: hash[:epoch_secret], joiner_secret: hash[:joiner_secret], psk_secret: hash[:psk_secret],
146
+ n_leaves: hash[:n_leaves], derived: hash[:derived], secret_tree_options: hash[:secret_tree_options] || {})
147
+ epoch_secrets.instance_variable_set(:@secret_tree, Melos::SecretTree.from_h(suite, hash[:secret_tree])) if hash[:secret_tree]
148
+ epoch_secrets
149
+ end
150
+
151
+ # 9: this epoch's secret tree, built on first use
152
+ def secret_tree
153
+ raise ArgumentError.new('n_leaves is needed to build the secret tree') if @n_leaves.nil?
154
+ @secret_tree ||= Melos::SecretTree.new(@suite, @n_leaves, encryption_secret, **@secret_tree_options)
155
+ end
156
+
157
+ private
158
+
159
+ def require_epoch_secret(name)
160
+ @epoch_secret or raise ArgumentError.new("#{name} is not available: this epoch has no epoch_secret")
161
+ end
162
+
163
+ def require_joiner_secret(name)
164
+ @joiner_secret or raise ArgumentError.new("#{name} is not available: this epoch has no joiner_secret")
165
+ end
166
+ end
@@ -0,0 +1,18 @@
1
+ module Melos
2
+ # Base class of everything melos raises on purpose. Plain ArgumentError is still used for
3
+ # mistakes in how the library is called (wrong object type, missing option, internal misuse).
4
+ class Error < StandardError; end
5
+
6
+ # Input that RFC 9420 says MUST be rejected: a malformed encoding, a signature, MAC or hash that
7
+ # does not verify, a proposal or commit that breaks the protocol's rules, a tree that fails its
8
+ # integrity checks. The message is not to be acted on.
9
+ class ProtocolError < Error; end
10
+
11
+ # An operation this group or client cannot perform in its current state: sending after being
12
+ # removed, sending application data while proposals are pending, a PSK or key we do not hold,
13
+ # a group_id already in use.
14
+ class StateError < Error; end
15
+
16
+ # A part of RFC 9420 this implementation does not provide yet. See docs/roadmap.md.
17
+ class UnsupportedError < Error; end
18
+ end
@@ -0,0 +1,78 @@
1
+ require 'securerandom'
2
+ require_relative 'crypto'
3
+ require_relative 'constants'
4
+ require_relative 'struct/structs'
5
+
6
+ # A party outside a group that may send it proposals (RFC 9420 Section 12.1.8): a signature key pair
7
+ # and a credential, listed in the group's external_senders GroupContext extension. It holds no group
8
+ # state; the caller supplies the group_id and epoch (known from a GroupInfo, say) and its index in
9
+ # the extension. Proposals go out as PublicMessages, since an external sender has no epoch secrets.
10
+ class Melos::ExternalSender
11
+ attr_reader :suite, :credential
12
+
13
+ # signature_private_key: an existing key, or nil to generate one
14
+ def initialize(cipher_suite_id, identity: '', credential: nil, signature_private_key: nil)
15
+ @suite = Melos::Crypto::CipherSuite.new(cipher_suite_id)
16
+ @signature_key_pair = signature_private_key ? @suite.pkey.deserialize_private_signature_key(signature_private_key) : Melos::Crypto.generate_signature_key_pair(@suite)
17
+ @credential = credential || Melos::Struct::Credential.create_basic_credential(identity)
18
+ end
19
+
20
+ def signature_private_key
21
+ Melos::Crypto.serialize_private_key(@suite, @signature_key_pair)
22
+ end
23
+
24
+ def signature_public_key
25
+ Melos::Crypto.serialize_public_key(@suite, @signature_key_pair)
26
+ end
27
+
28
+ # 12.1.8.1: this sender's entry in an external_senders extension
29
+ def external_sender
30
+ Melos::Struct::ExternalSender.create(signature_key: signature_public_key, credential: @credential)
31
+ end
32
+
33
+ # 12.1.8: sign and frame a Proposal from this sender, as an MLSMessage carrying a PublicMessage.
34
+ # sender_index: this sender's position in the group's external_senders extension
35
+ def create_proposal(proposal, group_id:, epoch:, sender_index:, authenticated_data: '')
36
+ unless Melos::Group::EXTERNAL_PROPOSAL_TYPES.include?(proposal.proposal_type)
37
+ raise ArgumentError.new("an external sender cannot send a proposal of type #{proposal.proposal_type}")
38
+ end
39
+ self.class.sign_proposal(@suite, signature_private_key, proposal, Melos::Struct::Sender.create_external(sender_index),
40
+ group_id: group_id, epoch: epoch, authenticated_data: authenticated_data)
41
+ end
42
+
43
+ # 12.1.1: propose adding a member by its KeyPackage (or the MLSMessage carrying it)
44
+ def create_add_proposal(key_package, **options)
45
+ key_package = key_package.key_package if key_package.is_a?(Melos::Struct::MLSMessage)
46
+ create_proposal(Melos::Struct::Proposal.create(proposal_type: Melos::Constants::ProposalType::ADD, add: Melos::Struct::Add.create(key_package: key_package)), **options)
47
+ end
48
+
49
+ # 12.1.3: propose removing the member at removed_leaf_index
50
+ def create_remove_proposal(removed_leaf_index, **options)
51
+ create_proposal(Melos::Struct::Proposal.create(proposal_type: Melos::Constants::ProposalType::REMOVE, remove: Melos::Struct::Remove.create(removed: removed_leaf_index)), **options)
52
+ end
53
+
54
+ # 12.1.4: propose injecting an external PSK the members know
55
+ def create_psk_proposal(psk_id, **options)
56
+ psk = Melos::Struct::PreSharedKey.create(
57
+ psk: Melos::Struct::PreSharedKeyID.create_external(psk_id: psk_id, psk_nonce: SecureRandom.random_bytes(@suite.kdf.n_h))
58
+ )
59
+ create_proposal(Melos::Struct::Proposal.create(proposal_type: Melos::Constants::ProposalType::PSK, psk: psk), **options)
60
+ end
61
+
62
+ # 12.1.7: propose replacing the GroupContext extensions
63
+ def create_group_context_extensions_proposal(extensions, **options)
64
+ gce = Melos::Struct::GroupContextExtensions.create(extensions: extensions)
65
+ create_proposal(Melos::Struct::Proposal.create(proposal_type: Melos::Constants::ProposalType::GROUP_CONTEXT_EXTENSIONS, group_context_extensions: gce), **options)
66
+ end
67
+
68
+ # 6.1: a proposal from outside the group, signed without a GroupContext, as a PublicMessage (no membership tag)
69
+ def self.sign_proposal(suite, signature_private_key, proposal, sender, group_id:, epoch:, authenticated_data: '')
70
+ framed_content = Melos::Struct::FramedContent.create(
71
+ group_id: group_id, epoch: epoch, sender: sender, authenticated_data: authenticated_data,
72
+ content_type: Melos::Constants::ContentType::PROPOSAL, content: proposal
73
+ )
74
+ authenticated_content = Melos::Struct::AuthenticatedContent.create(wire_format: Melos::Constants::WireFormat::MLS_PUBLIC_MESSAGE, content: framed_content, auth: nil)
75
+ authenticated_content.sign(suite, signature_private_key, nil)
76
+ Melos::Struct::MLSMessage.create(public_message: Melos::Struct::PublicMessage.protect(authenticated_content, suite, nil, nil))
77
+ end
78
+ end
@@ -0,0 +1,310 @@
1
+ # Validation of the pieces that enter a group: proposal lists (12.2), UpdatePaths (12.4.2),
2
+ # KeyPackages (10.1) and LeafNodes (7.3). All methods raise Melos::ProtocolError on failure.
3
+ class Melos::Group
4
+ # 7.2: the proposal and extension types every client implements; they are not listed in Capabilities
5
+ DEFAULT_PROPOSAL_TYPES = (0x0001..0x0007).to_a.freeze
6
+ DEFAULT_EXTENSION_TYPES = (0x0001..0x0005).to_a.freeze
7
+
8
+ # 7.2: applications MUST define a maximum acceptable leaf node lifetime (seconds) and pass it as
9
+ # max_leaf_node_lifetime. There is no default limit: interop test vectors use the full uint64 range.
10
+ DEFAULT_MAX_LEAF_NODE_LIFETIME = nil
11
+
12
+ # 5.3.1: credentials are validated by the application's Authentication Service. Without one,
13
+ # only basic credentials are accepted, since nothing else can be checked here.
14
+ DEFAULT_CREDENTIAL_VALIDATOR = ->(credential, _leaf_node) { credential.credential_type == Melos::Constants::CredentialType::BASIC }
15
+
16
+ private
17
+
18
+ # 12.2: the rules a regular commit's proposal list must satisfy as a whole; proposals is [proposal, sender] pairs.
19
+ # "The same client" is taken to mean the same signature key, which the RFC leaves to the application.
20
+ def validate_proposal_list!(proposals, committer)
21
+ of_type = ->(type) { proposals.select { |proposal, _sender| proposal.proposal_type == type } }
22
+ updates = of_type.(Melos::Constants::ProposalType::UPDATE)
23
+ removes = of_type.(Melos::Constants::ProposalType::REMOVE)
24
+ adds = of_type.(Melos::Constants::ProposalType::ADD)
25
+ psks = of_type.(Melos::Constants::ProposalType::PSK)
26
+ gces = of_type.(Melos::Constants::ProposalType::GROUP_CONTEXT_EXTENSIONS)
27
+
28
+ raise Melos::ProtocolError.new('commit contains an Update from the committer') if updates.any? { |_proposal, sender| sender == committer }
29
+ removed = removes.map { |proposal, _sender| proposal.remove.removed }
30
+ raise Melos::ProtocolError.new('commit removes its own sender') if removed.include?(committer)
31
+ touched = updates.map { |_proposal, sender| sender } + removed
32
+ repeated = touched.tally.select { |_leaf, count| count > 1 }.keys
33
+ raise Melos::ProtocolError.new("more than one Update or Remove for leaf #{repeated.join(', ')}") unless repeated.empty?
34
+
35
+ added_keys = adds.map { |proposal, _sender| proposal.add.key_package.leaf_node.signature_key }
36
+ raise Melos::ProtocolError.new('more than one Add for the same client') unless added_keys.uniq.size == added_keys.size
37
+ staying_keys = []
38
+ @ratchet_tree.each_leaf_node { |leaf_node, leaf_index| staying_keys << leaf_node.signature_key unless removed.include?(leaf_index) }
39
+ raise Melos::ProtocolError.new('Add for a client already in the group') unless (added_keys & staying_keys).empty?
40
+
41
+ psk_ids = psks.map { |proposal, _sender| proposal.psk.psk.raw }
42
+ raise Melos::ProtocolError.new('more than one PreSharedKey proposal for the same PreSharedKeyID') unless psk_ids.uniq.size == psk_ids.size
43
+ raise Melos::ProtocolError.new('more than one GroupContextExtensions proposal') if gces.size > 1
44
+
45
+ reinits = of_type.(Melos::Constants::ProposalType::REINIT)
46
+ raise Melos::ProtocolError.new('a ReInit proposal must be the only proposal of its commit') if reinits.any? && proposals.size > 1
47
+ reinits.each do |proposal, _sender|
48
+ # 12.1.5: a ReInit must not go to a lower version
49
+ raise Melos::ProtocolError.new("ReInit to version #{proposal.reinit.version}, lower than the group's") if proposal.reinit.version < Melos::Constants::Version::MLS10
50
+ Melos::Struct::Extension.check_unique_types!(proposal.reinit.extensions, 'ReInit extensions')
51
+ end
52
+ # ExternalInit must be absent (12.2); apply_proposals rejects it outside an external commit
53
+ end
54
+
55
+ # 12.2: an external commit's list is exactly one ExternalInit, at most one Remove, and PreSharedKeys
56
+ def validate_external_proposal_list!(proposals)
57
+ types = proposals.map { |proposal, _sender| proposal.proposal_type }
58
+ raise Melos::ProtocolError.new('an external commit must have exactly one ExternalInit') unless types.count(Melos::Constants::ProposalType::EXTERNAL_INIT) == 1
59
+ raise Melos::ProtocolError.new('an external commit may have at most one Remove') if types.count(Melos::Constants::ProposalType::REMOVE) > 1
60
+ allowed = [Melos::Constants::ProposalType::EXTERNAL_INIT, Melos::Constants::ProposalType::REMOVE, Melos::Constants::ProposalType::PSK]
61
+ others = types - allowed
62
+ raise Melos::ProtocolError.new("an external commit cannot carry #{others.map { Melos::Constants::ProposalType::NAMES[_1] || _1 }.join(', ')} proposals") unless others.empty?
63
+ psk_ids = proposals.filter_map { |proposal, _sender| proposal.psk.psk.raw if proposal.proposal_type == Melos::Constants::ProposalType::PSK }
64
+ raise Melos::ProtocolError.new('more than one PreSharedKey proposal for the same PreSharedKeyID') unless psk_ids.uniq.size == psk_ids.size
65
+ end
66
+
67
+ # 12.2: in a resync external commit, the new leaf must be acceptable as an Update of the leaf it removes;
68
+ # here, that the application's member_matcher takes them for the same member
69
+ def validate_resync!(proposals, leaf_node)
70
+ remove = proposals.find { |proposal, _sender| proposal.proposal_type == Melos::Constants::ProposalType::REMOVE }&.first
71
+ return if remove.nil?
72
+ removed_leaf = @ratchet_tree.leaf_node_at(remove.remove.removed)
73
+ return if removed_leaf && @member_matcher.call(removed_leaf, leaf_node)
74
+ raise Melos::ProtocolError.new('an external commit may only remove an earlier appearance of its committer')
75
+ end
76
+
77
+ # 11.2, 11.3, 12.4.3.1: a group joined with a reinit or branch resumption PSK (psk_id) is checked against
78
+ # the group it resumes (old_group): epoch 1, the ReInit's parameters or the old group's suite, and the membership
79
+ def validate_resumption!(psk_id, old_group, member_matcher)
80
+ raise Melos::StateError.new('the group this Welcome resumes is not known') if old_group.nil?
81
+ raise Melos::ProtocolError.new("a resumed group must start in epoch 1, not #{@epoch}") unless @epoch == 1
82
+ old_leaves = []
83
+ old_group.ratchet_tree.each_leaf_node { |leaf_node, _index| old_leaves << leaf_node }
84
+ new_leaves = []
85
+ @ratchet_tree.each_leaf_node { |leaf_node, _index| new_leaves << leaf_node }
86
+ case psk_id.usage
87
+ when Melos::Constants::ResumptionPSKUsage::REINIT
88
+ reinit = old_group.pending_reinit
89
+ raise Melos::ProtocolError.new('the resumed group was not reinitialized') if reinit.nil?
90
+ raise Melos::ProtocolError.new('the reinit PSK is not from the epoch the ReInit was committed in') unless psk_id.psk_epoch == old_group.epoch
91
+ raise Melos::ProtocolError.new('group_id differs from the ReInit') unless @group_id == reinit.group_id
92
+ raise Melos::ProtocolError.new('version differs from the ReInit') unless group_context.version == reinit.version
93
+ raise Melos::ProtocolError.new('cipher suite differs from the ReInit') unless @suite.suite_id == reinit.cipher_suite
94
+ raise Melos::ProtocolError.new('extensions differ from the ReInit') unless @extensions.map(&:raw) == reinit.extensions.map(&:raw)
95
+ # every member of the old group is in the new one
96
+ missing = old_leaves.reject { |old| new_leaves.any? { member_matcher.call(old, _1) } }
97
+ raise Melos::ProtocolError.new('a member of the reinitialized group is missing from the new group') unless missing.empty?
98
+ when Melos::Constants::ResumptionPSKUsage::BRANCH
99
+ raise Melos::ProtocolError.new('a branch must keep the cipher suite of its group') unless @suite.suite_id == old_group.suite.suite_id
100
+ # every member of the new group was in the old one
101
+ extra = new_leaves.reject { |new| old_leaves.any? { member_matcher.call(_1, new) } }
102
+ raise Melos::ProtocolError.new('a member of the branch is not in the group it branches from') unless extra.empty?
103
+ end
104
+ end
105
+
106
+ # 12.4.2, 7.6, 7.9.2: a received UpdatePath, checked against the tree after the proposals and before the merge.
107
+ # new_leaf: the committer joined by this commit (12.4.3.2), so its leaf in tree is the path's own and replaces nothing
108
+ def validate_update_path!(tree, update_path, committer, joiners, extensions, new_leaf: false)
109
+ leaf_node = update_path.leaf_node
110
+ validate_leaf_node!(leaf_node, context: :commit, leaf_index: committer, tree: tree, extensions: extensions,
111
+ replacing: new_leaf ? nil : tree.leaf_node_at(committer), sending: false)
112
+ # 7.9.2: the parent hash in the new leaf is the one this tree and path imply
113
+ raise Melos::ProtocolError.new('UpdatePath leaf node parent hash does not verify') unless tree.verify_parent_hash_of_path(committer, update_path)
114
+ # 12.4.2, 16.7: the path's public keys are new to the tree and distinct from each other
115
+ path_keys = [leaf_node.encryption_key] + update_path.nodes.map(&:encryption_key)
116
+ raise Melos::ProtocolError.new('UpdatePath public keys are not distinct') unless path_keys.uniq.size == path_keys.size
117
+ # (the committer's own leaf is left out: 7.3 above already requires a new key, and a joiner's leaf is the path's)
118
+ tree_keys = tree.nodes.each_with_index.filter_map { |node, index| node&.public_encryption_key unless index == committer * 2 }
119
+ raise Melos::ProtocolError.new('a public key in the UpdatePath already appears in the tree') unless (path_keys & tree_keys).empty?
120
+ # 7.6: each node carries one ciphertext per member of its copath resolution, the new leaves excluded
121
+ copath_nodes = tree.copath_nodes_of_filtered_direct_path(committer * 2)
122
+ raise Melos::ProtocolError.new('malformed update path') unless copath_nodes.count == update_path.nodes.count
123
+ excluded = joiners.map { _1.leaf_index * 2 }
124
+ update_path.nodes.each_with_index do |node, i|
125
+ expected = (tree.resolution(copath_nodes[i]) - excluded).count
126
+ next if node.encrypted_path_secret.count == expected
127
+ raise Melos::ProtocolError.new("UpdatePath node #{i} has #{node.encrypted_path_secret.count} ciphertexts, expected #{expected}")
128
+ end
129
+ end
130
+
131
+
132
+ # 10.1: a KeyPackage being added, in the tree it is (or will be) added to.
133
+ # leaf_index: where it sits in tree, or nil if it is not in tree yet
134
+ def validate_key_package!(key_package, tree:, leaf_index:, extensions:, sending:)
135
+ raise Melos::ProtocolError.new("KeyPackage has version #{key_package.version}") unless key_package.version == Melos::Constants::Version::MLS10
136
+ raise Melos::ProtocolError.new("KeyPackage is for cipher suite #{key_package.cipher_suite}") unless key_package.cipher_suite == @suite.suite_id
137
+ Melos::Struct::Extension.check_unique_types!(key_package.extensions, 'KeyPackage extensions')
138
+ validate_leaf_node!(key_package.leaf_node, context: :key_package, leaf_index: leaf_index, tree: tree, extensions: extensions, sending: sending)
139
+ raise Melos::ProtocolError.new('KeyPackage signature does not verify') unless key_package.verify
140
+ raise Melos::ProtocolError.new('KeyPackage init_key equals its leaf encryption_key') if key_package.init_key == key_package.leaf_node.encryption_key
141
+ # 10: extensions of the KeyPackage itself must also be in the leaf's capabilities
142
+ unsupported = key_package.extensions.map(&:extension_type) - DEFAULT_EXTENSION_TYPES - key_package.leaf_node.capabilities.export.extensions
143
+ raise Melos::ProtocolError.new("KeyPackage extensions not in its capabilities: #{unsupported.map { '0x%04x' % _1 }.join(', ')}") unless unsupported.empty?
144
+ end
145
+
146
+ # 7.3: a LeafNode in one of its contexts.
147
+ # context: :key_package (in a KeyPackage), :update (an Update proposal), :commit (the leaf of an UpdatePath),
148
+ # or :tree (a leaf already in the tree, e.g. when joining; its source is taken as given)
149
+ # leaf_index: the leaf's index in tree (needed to verify update/commit signatures); nil if not in tree yet
150
+ # tree, extensions: the ratchet tree and GroupContext extensions the leaf must be compatible with
151
+ # replacing: for :update and :commit, the leaf node being replaced
152
+ # sending: the leaf is in a message we are about to send, so its lifetime is checked against the current time
153
+ def validate_leaf_node!(leaf_node, context:, leaf_index:, tree:, extensions:, replacing: nil, sending: false)
154
+ expected_source = { key_package: Melos::Constants::LeafNodeSource::KEY_PACKAGE, update: Melos::Constants::LeafNodeSource::UPDATE,
155
+ commit: Melos::Constants::LeafNodeSource::COMMIT }[context]
156
+ if expected_source && leaf_node.leaf_node_source != expected_source
157
+ raise Melos::ProtocolError.new("leaf node source is #{leaf_node.leaf_node_source}, expected #{expected_source} for #{context}")
158
+ end
159
+
160
+ # 5.3.1: the credential, by the application
161
+ raise Melos::ProtocolError.new('leaf node credential rejected') unless @credential_validator.call(leaf_node.credential, leaf_node)
162
+
163
+ # the signature; update and commit leaves are bound to this group and leaf index
164
+ verified = if leaf_node.leaf_node_source == Melos::Constants::LeafNodeSource::KEY_PACKAGE
165
+ leaf_node.verify(@suite, nil, nil)
166
+ else
167
+ raise ArgumentError.new('leaf index needed to verify this leaf node') if leaf_index.nil?
168
+ leaf_node.verify(@suite, @group_id, leaf_index)
169
+ end
170
+ raise Melos::ProtocolError.new('leaf node signature does not verify') unless verified
171
+
172
+ # 7.3, 11: compatible with the group's version, extensions and required capabilities. The leaf's
173
+ # cipher_suites list is not checked against the group's suite: 7.3 does not require it, other
174
+ # implementations leave it out (the interop vectors do), and an added KeyPackage's own cipher_suite
175
+ # is checked against the group's in validate_key_package!.
176
+ capabilities = leaf_node.capabilities.export
177
+ raise Melos::ProtocolError.new('leaf node does not support MLS 1.0') unless capabilities.versions.include?(Melos::Constants::Version::MLS10)
178
+ others = []
179
+ tree.each_leaf_node { |other, index| others << other unless index == leaf_index }
180
+ validate_capabilities!(leaf_node, capabilities, extensions, others.map { _1.credential.credential_type })
181
+ # 7.3, 13.3: the other members support this leaf's credential type
182
+ others.each do |other|
183
+ next if other.capabilities.export.credentials.include?(leaf_node.credential.credential_type)
184
+ raise Melos::ProtocolError.new('a current member does not support this leaf node\'s credential type')
185
+ end
186
+
187
+ # 7.2, 7.3: lifetime, for leaves that came from a KeyPackage
188
+ if leaf_node.leaf_node_source == Melos::Constants::LeafNodeSource::KEY_PACKAGE
189
+ lifetime = leaf_node.lifetime
190
+ if @max_leaf_node_lifetime && lifetime.not_after - lifetime.not_before > @max_leaf_node_lifetime
191
+ raise Melos::ProtocolError.new('leaf node lifetime is longer than allowed')
192
+ end
193
+ if sending
194
+ now = Time.now.to_i
195
+ raise Melos::ProtocolError.new('leaf node lifetime does not cover the current time') unless lifetime.not_before <= now && now <= lifetime.not_after
196
+ end
197
+ end
198
+
199
+ Melos::Struct::Extension.check_unique_types!(leaf_node.extensions, 'leaf node extensions')
200
+
201
+ # 7.3, 12.4.2: a replacement leaf brings a new encryption key
202
+ if replacing && leaf_node.encryption_key == replacing.encryption_key
203
+ raise Melos::ProtocolError.new('replacement leaf node reuses the encryption key of the leaf it replaces')
204
+ end
205
+ # 7.3, 16.7: keys are unique among members
206
+ others.each do |other|
207
+ raise Melos::ProtocolError.new('leaf node signature key is already used by another member') if other.signature_key == leaf_node.signature_key
208
+ raise Melos::ProtocolError.new('leaf node encryption key is already used by another member') if other.encryption_key == leaf_node.encryption_key
209
+ end
210
+ end
211
+
212
+ # 7.2, 7.3, 11.1, 13.4: a leaf's capabilities cover its own extensions and credential type, the group's
213
+ # non-default extensions, the required_capabilities extension if any, and the credential types in use
214
+ def validate_capabilities!(leaf_node, capabilities, extensions, credential_types_in_use)
215
+ own_extension_types = leaf_node.extensions.map(&:extension_type) - DEFAULT_EXTENSION_TYPES
216
+ missing = own_extension_types - capabilities.extensions
217
+ raise Melos::ProtocolError.new("leaf node extensions not in its capabilities: #{missing.map { '0x%04x' % _1 }.join(', ')}") unless missing.empty?
218
+ raise Melos::ProtocolError.new('leaf node credential type not in its capabilities') unless capabilities.credentials.include?(leaf_node.credential.credential_type)
219
+
220
+ group_extension_types = extensions.map(&:extension_type) - DEFAULT_EXTENSION_TYPES
221
+ missing = group_extension_types - capabilities.extensions
222
+ raise Melos::ProtocolError.new("leaf node does not support GroupContext extensions #{missing.map { '0x%04x' % _1 }.join(', ')}") unless missing.empty?
223
+
224
+ if (required = required_capabilities(extensions))
225
+ missing = (required.extension_types - DEFAULT_EXTENSION_TYPES) - capabilities.extensions
226
+ raise Melos::ProtocolError.new("leaf node lacks required extensions #{missing.map { '0x%04x' % _1 }.join(', ')}") unless missing.empty?
227
+ missing = (required.proposal_types - DEFAULT_PROPOSAL_TYPES) - capabilities.proposals
228
+ raise Melos::ProtocolError.new("leaf node lacks required proposal types #{missing.map { '0x%04x' % _1 }.join(', ')}") unless missing.empty?
229
+ missing = required.credential_types - capabilities.credentials
230
+ raise Melos::ProtocolError.new("leaf node lacks required credential types #{missing.join(', ')}") unless missing.empty?
231
+ end
232
+
233
+ missing = credential_types_in_use.uniq - capabilities.credentials
234
+ raise Melos::ProtocolError.new("leaf node does not support credential types in use: #{missing.join(', ')}") unless missing.empty?
235
+ end
236
+
237
+ # 12.2, 12.1.7: after a proposal list is applied, every remaining member is compatible with the (possibly
238
+ # new) extensions and with every other member, and keys are unique. Signatures were checked when each leaf
239
+ # entered the tree, so they are not verified again here.
240
+ def validate_members!(tree, extensions)
241
+ leaves = []
242
+ tree.each_leaf_node { |leaf_node, _index| leaves << leaf_node }
243
+ signature_keys = leaves.map(&:signature_key)
244
+ raise Melos::ProtocolError.new('two members share a signature key') unless signature_keys.uniq.size == signature_keys.size
245
+ encryption_keys = leaves.map(&:encryption_key)
246
+ raise Melos::ProtocolError.new('two members share an encryption key') unless encryption_keys.uniq.size == encryption_keys.size
247
+ credential_types = leaves.map { _1.credential.credential_type }
248
+ leaves.each do |leaf_node|
249
+ validate_capabilities!(leaf_node, leaf_node.capabilities.export, extensions, credential_types)
250
+ end
251
+ end
252
+
253
+ # 5.3.1, 12.1.8.1: an external_senders extension parses, and each sender's credential is validated by the
254
+ # application's Authentication Service (the credential_validator gets the ExternalSender as the holder)
255
+ def validate_external_senders!(extensions)
256
+ external_senders(extensions).each do |external_sender|
257
+ next if @credential_validator.call(external_sender.credential, external_sender)
258
+ raise Melos::ProtocolError.new('external sender credential rejected')
259
+ end
260
+ end
261
+
262
+ # 12.4.3.1: what a new member checks about the state it was welcomed into, once it is assembled
263
+ def validate_joined_state!
264
+ validate_tree!(@ratchet_tree, @extensions)
265
+ validate_external_senders!(@extensions)
266
+ # the private keys derived from the Welcome's path secret must be the ones for the public keys in the tree
267
+ raise Melos::ProtocolError.new('derived private keys do not match the ratchet tree') unless @private_tree.consistent?(@ratchet_tree)
268
+ end
269
+
270
+ # 12.4.3.1, 7.9.2, 7.3: the integrity of a ratchet tree received from someone else.
271
+ # Also what makes 13.4 hold for us: validate_leaf_node! on our own leaf checks that we support every GroupContext extension.
272
+ def validate_tree!(tree, extensions)
273
+ raise Melos::ProtocolError.new('ratchet tree has a parent node that is not parent-hash valid') unless tree.parent_hash_valid?
274
+ tree.each_leaf_node do |leaf_node, leaf_index|
275
+ validate_leaf_node!(leaf_node, context: :tree, leaf_index: leaf_index, tree: tree, extensions: extensions)
276
+ end
277
+
278
+ encryption_keys = []
279
+ tree.each_leaf_node { |leaf_node, _index| encryption_keys << leaf_node.encryption_key }
280
+ tree.nodes.each_with_index do |node, node_index|
281
+ next if node.nil? || node.parent_node.nil?
282
+ parent_node = node.parent_node
283
+ encryption_keys << parent_node.encryption_key
284
+ parent_node.unmerged_leaves.each do |leaf_index|
285
+ raise Melos::ProtocolError.new("unmerged leaf #{leaf_index} is blank") if tree.leaf_node_at(leaf_index).nil?
286
+ direct_path = Melos::Tree.direct_path(leaf_index * 2, tree.n_leaves)
287
+ raise Melos::ProtocolError.new("unmerged leaf #{leaf_index} is not under node #{node_index}") unless direct_path.include?(node_index)
288
+ # every non-blank node between the leaf and this node lists the leaf as unmerged too
289
+ direct_path.take_while { _1 != node_index }.each do |between|
290
+ next if tree[between].nil?
291
+ next if tree[between].parent_node.unmerged_leaves.include?(leaf_index)
292
+ raise Melos::ProtocolError.new("unmerged leaf #{leaf_index} of node #{node_index} is merged at node #{between} below it")
293
+ end
294
+ end
295
+ end
296
+ # 12.4.3.1, 16.7: no encryption key appears in two nodes
297
+ raise Melos::ProtocolError.new('an encryption key appears in more than one node of the ratchet tree') unless encryption_keys.uniq.size == encryption_keys.size
298
+ end
299
+
300
+ # 11.1: the required_capabilities extension of a GroupContext, decoded, or nil.
301
+ # Returns an object with extension_types, proposal_types and credential_types as integer arrays.
302
+ def required_capabilities(extensions)
303
+ extension = extensions.find { _1.extension_type == Melos::Constants::ExtensionType::REQUIRED_CAPABILITIES }
304
+ return nil if extension.nil?
305
+ struct = Melos::Struct::RequiredCapabilities.new(extension.extension_data)
306
+ Struct.new(:extension_types, :proposal_types, :credential_types).new(
307
+ struct.extension_types.unpack('S>*'), struct.proposal_types.unpack('S>*'), struct.credential_types.unpack('S>*')
308
+ )
309
+ end
310
+ end