1 package org
.asamk
.signal
.manager
.helper
;
3 import com
.google
.protobuf
.InvalidProtocolBufferException
;
5 import org
.asamk
.signal
.manager
.groups
.GroupLinkPassword
;
6 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
7 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
8 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
9 import org
.asamk
.signal
.manager
.storage
.recipients
.Profile
;
10 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
11 import org
.asamk
.signal
.manager
.util
.IOUtils
;
12 import org
.signal
.storageservice
.protos
.groups
.AccessControl
;
13 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
14 import org
.signal
.storageservice
.protos
.groups
.Member
;
15 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
16 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroupChange
;
17 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroupJoinInfo
;
18 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedPendingMember
;
19 import org
.signal
.zkgroup
.InvalidInputException
;
20 import org
.signal
.zkgroup
.VerificationFailedException
;
21 import org
.signal
.zkgroup
.groups
.GroupMasterKey
;
22 import org
.signal
.zkgroup
.groups
.GroupSecretParams
;
23 import org
.signal
.zkgroup
.groups
.UuidCiphertext
;
24 import org
.slf4j
.Logger
;
25 import org
.slf4j
.LoggerFactory
;
26 import org
.whispersystems
.libsignal
.util
.Pair
;
27 import org
.whispersystems
.libsignal
.util
.guava
.Optional
;
28 import org
.whispersystems
.signalservice
.api
.groupsv2
.DecryptedGroupUtil
;
29 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupCandidate
;
30 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
31 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Api
;
32 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
33 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
34 import org
.whispersystems
.signalservice
.api
.groupsv2
.InvalidGroupStateException
;
35 import org
.whispersystems
.signalservice
.api
.groupsv2
.NotAbleToApplyGroupV2ChangeException
;
36 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
37 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
40 import java
.io
.FileInputStream
;
41 import java
.io
.IOException
;
42 import java
.io
.InputStream
;
44 import java
.util
.UUID
;
45 import java
.util
.stream
.Collectors
;
47 public class GroupV2Helper
{
49 private final static Logger logger
= LoggerFactory
.getLogger(GroupV2Helper
.class);
51 private final ProfileKeyCredentialProvider profileKeyCredentialProvider
;
53 private final ProfileProvider profileProvider
;
55 private final SelfRecipientIdProvider selfRecipientIdProvider
;
57 private final GroupsV2Operations groupsV2Operations
;
59 private final GroupsV2Api groupsV2Api
;
61 private final GroupAuthorizationProvider groupAuthorizationProvider
;
63 private final SignalServiceAddressResolver addressResolver
;
66 final ProfileKeyCredentialProvider profileKeyCredentialProvider
,
67 final ProfileProvider profileProvider
,
68 final SelfRecipientIdProvider selfRecipientIdProvider
,
69 final GroupsV2Operations groupsV2Operations
,
70 final GroupsV2Api groupsV2Api
,
71 final GroupAuthorizationProvider groupAuthorizationProvider
,
72 final SignalServiceAddressResolver addressResolver
74 this.profileKeyCredentialProvider
= profileKeyCredentialProvider
;
75 this.profileProvider
= profileProvider
;
76 this.selfRecipientIdProvider
= selfRecipientIdProvider
;
77 this.groupsV2Operations
= groupsV2Operations
;
78 this.groupsV2Api
= groupsV2Api
;
79 this.groupAuthorizationProvider
= groupAuthorizationProvider
;
80 this.addressResolver
= addressResolver
;
83 public DecryptedGroup
getDecryptedGroup(final GroupSecretParams groupSecretParams
) {
85 final var groupsV2AuthorizationString
= groupAuthorizationProvider
.getAuthorizationForToday(
87 return groupsV2Api
.getGroup(groupSecretParams
, groupsV2AuthorizationString
);
88 } catch (IOException
| VerificationFailedException
| InvalidGroupStateException e
) {
89 logger
.warn("Failed to retrieve Group V2 info, ignoring: {}", e
.getMessage());
94 public DecryptedGroupJoinInfo
getDecryptedGroupJoinInfo(
95 GroupMasterKey groupMasterKey
, GroupLinkPassword password
96 ) throws IOException
, GroupLinkNotActiveException
{
97 var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
99 return groupsV2Api
.getGroupJoinInfo(groupSecretParams
,
100 Optional
.fromNullable(password
).transform(GroupLinkPassword
::serialize
),
101 groupAuthorizationProvider
.getAuthorizationForToday(groupSecretParams
));
104 public Pair
<GroupInfoV2
, DecryptedGroup
> createGroup(
105 String name
, Set
<RecipientId
> members
, File avatarFile
106 ) throws IOException
{
107 final var avatarBytes
= readAvatarBytes(avatarFile
);
108 final var newGroup
= buildNewGroup(name
, members
, avatarBytes
);
109 if (newGroup
== null) {
113 final var groupSecretParams
= newGroup
.getGroupSecretParams();
115 final GroupsV2AuthorizationString groupAuthForToday
;
116 final DecryptedGroup decryptedGroup
;
118 groupAuthForToday
= groupAuthorizationProvider
.getAuthorizationForToday(groupSecretParams
);
119 groupsV2Api
.putNewGroup(newGroup
, groupAuthForToday
);
120 decryptedGroup
= groupsV2Api
.getGroup(groupSecretParams
, groupAuthForToday
);
121 } catch (IOException
| VerificationFailedException
| InvalidGroupStateException e
) {
122 logger
.warn("Failed to create V2 group: {}", e
.getMessage());
125 if (decryptedGroup
== null) {
126 logger
.warn("Failed to create V2 group, unknown error!");
130 final var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
131 final var masterKey
= groupSecretParams
.getMasterKey();
132 var g
= new GroupInfoV2(groupId
, masterKey
);
134 return new Pair
<>(g
, decryptedGroup
);
137 private byte[] readAvatarBytes(final File avatarFile
) throws IOException
{
138 final byte[] avatarBytes
;
139 try (InputStream avatar
= avatarFile
== null ?
null : new FileInputStream(avatarFile
)) {
140 avatarBytes
= avatar
== null ?
null : IOUtils
.readFully(avatar
);
145 private GroupsV2Operations
.NewGroup
buildNewGroup(
146 String name
, Set
<RecipientId
> members
, byte[] avatar
148 final var profileKeyCredential
= profileKeyCredentialProvider
.getProfileKeyCredential(selfRecipientIdProvider
.getSelfRecipientId());
149 if (profileKeyCredential
== null) {
150 logger
.warn("Cannot create a V2 group as self does not have a versioned profile");
154 if (!areMembersValid(members
)) return null;
156 var self
= new GroupCandidate(addressResolver
.resolveSignalServiceAddress(selfRecipientIdProvider
.getSelfRecipientId())
158 .orNull(), Optional
.fromNullable(profileKeyCredential
));
159 var candidates
= members
.stream()
160 .map(member
-> new GroupCandidate(addressResolver
.resolveSignalServiceAddress(member
).getUuid().get(),
161 Optional
.fromNullable(profileKeyCredentialProvider
.getProfileKeyCredential(member
))))
162 .collect(Collectors
.toSet());
164 final var groupSecretParams
= GroupSecretParams
.generate();
165 return groupsV2Operations
.createNewGroup(groupSecretParams
,
167 Optional
.fromNullable(avatar
),
174 private boolean areMembersValid(final Set
<RecipientId
> members
) {
175 final var noUuidCapability
= members
.stream()
176 .map(addressResolver
::resolveSignalServiceAddress
)
177 .filter(address
-> !address
.getUuid().isPresent())
178 .map(SignalServiceAddress
::getLegacyIdentifier
)
179 .collect(Collectors
.toSet());
180 if (noUuidCapability
.size() > 0) {
181 logger
.warn("Cannot create a V2 group as some members don't have a UUID: {}",
182 String
.join(", ", noUuidCapability
));
186 final var noGv2Capability
= members
.stream()
187 .map(profileProvider
::getProfile
)
188 .filter(profile
-> profile
!= null && !profile
.getCapabilities().contains(Profile
.Capability
.gv2
))
189 .collect(Collectors
.toSet());
190 if (noGv2Capability
.size() > 0) {
191 logger
.warn("Cannot create a V2 group as some members don't support Groups V2: {}",
192 noGv2Capability
.stream().map(Profile
::getDisplayName
).collect(Collectors
.joining(", ")));
199 public Pair
<DecryptedGroup
, GroupChange
> updateGroup(
200 GroupInfoV2 groupInfoV2
, String name
, String description
, File avatarFile
201 ) throws IOException
{
202 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupInfoV2
.getMasterKey());
203 var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
205 var change
= name
!= null ? groupOperations
.createModifyGroupTitle(name
) : GroupChange
.Actions
.newBuilder();
207 if (description
!= null) {
208 change
.setModifyDescription(groupOperations
.createModifyGroupDescription(description
));
211 if (avatarFile
!= null) {
212 final var avatarBytes
= readAvatarBytes(avatarFile
);
213 var avatarCdnKey
= groupsV2Api
.uploadAvatar(avatarBytes
,
215 groupAuthorizationProvider
.getAuthorizationForToday(groupSecretParams
));
216 change
.setModifyAvatar(GroupChange
.Actions
.ModifyAvatarAction
.newBuilder().setAvatar(avatarCdnKey
));
219 final var uuid
= addressResolver
.resolveSignalServiceAddress(this.selfRecipientIdProvider
.getSelfRecipientId())
221 if (uuid
.isPresent()) {
222 change
.setSourceUuid(UuidUtil
.toByteString(uuid
.get()));
225 return commitChange(groupInfoV2
, change
);
228 public Pair
<DecryptedGroup
, GroupChange
> addMembers(
229 GroupInfoV2 groupInfoV2
, Set
<RecipientId
> newMembers
230 ) throws IOException
{
231 GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
233 if (!areMembersValid(newMembers
)) {
234 throw new IOException("Failed to update group");
237 var candidates
= newMembers
.stream()
238 .map(member
-> new GroupCandidate(addressResolver
.resolveSignalServiceAddress(member
).getUuid().get(),
239 Optional
.fromNullable(profileKeyCredentialProvider
.getProfileKeyCredential(member
))))
240 .collect(Collectors
.toSet());
242 final var uuid
= addressResolver
.resolveSignalServiceAddress(selfRecipientIdProvider
.getSelfRecipientId())
245 final var change
= groupOperations
.createModifyGroupMembershipChange(candidates
, uuid
);
247 change
.setSourceUuid(UuidUtil
.toByteString(uuid
));
249 return commitChange(groupInfoV2
, change
);
252 public Pair
<DecryptedGroup
, GroupChange
> leaveGroup(GroupInfoV2 groupInfoV2
) throws IOException
{
253 var pendingMembersList
= groupInfoV2
.getGroup().getPendingMembersList();
254 final var selfUuid
= addressResolver
.resolveSignalServiceAddress(selfRecipientIdProvider
.getSelfRecipientId())
257 var selfPendingMember
= DecryptedGroupUtil
.findPendingByUuid(pendingMembersList
, selfUuid
);
259 if (selfPendingMember
.isPresent()) {
260 return revokeInvites(groupInfoV2
, Set
.of(selfPendingMember
.get()));
262 return ejectMembers(groupInfoV2
, Set
.of(selfUuid
));
266 public Pair
<DecryptedGroup
, GroupChange
> removeMembers(
267 GroupInfoV2 groupInfoV2
, Set
<RecipientId
> members
268 ) throws IOException
{
269 final var memberUuids
= members
.stream()
270 .map(addressResolver
::resolveSignalServiceAddress
)
271 .map(SignalServiceAddress
::getUuid
)
272 .filter(Optional
::isPresent
)
274 .collect(Collectors
.toSet());
275 return ejectMembers(groupInfoV2
, memberUuids
);
278 public Pair
<DecryptedGroup
, GroupChange
> revokeInvitedMembers(
279 GroupInfoV2 groupInfoV2
, Set
<RecipientId
> members
280 ) throws IOException
{
281 var pendingMembersList
= groupInfoV2
.getGroup().getPendingMembersList();
282 final var memberUuids
= members
.stream()
283 .map(addressResolver
::resolveSignalServiceAddress
)
284 .map(SignalServiceAddress
::getUuid
)
285 .filter(Optional
::isPresent
)
287 .map(uuid
-> DecryptedGroupUtil
.findPendingByUuid(pendingMembersList
, uuid
))
288 .filter(Optional
::isPresent
)
290 .collect(Collectors
.toSet());
291 return revokeInvites(groupInfoV2
, memberUuids
);
294 public Pair
<DecryptedGroup
, GroupChange
> resetGroupLinkPassword(GroupInfoV2 groupInfoV2
) throws IOException
{
295 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
296 final var newGroupLinkPassword
= GroupLinkPassword
.createNew().serialize();
297 final var change
= groupOperations
.createModifyGroupLinkPasswordChange(newGroupLinkPassword
);
298 return commitChange(groupInfoV2
, change
);
301 public Pair
<DecryptedGroup
, GroupChange
> setGroupLinkState(
302 GroupInfoV2 groupInfoV2
, GroupLinkState state
303 ) throws IOException
{
304 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
306 final var accessRequired
= toAccessControl(state
);
307 final var requiresNewPassword
= state
!= GroupLinkState
.DISABLED
&& groupInfoV2
.getGroup()
308 .getInviteLinkPassword()
311 final var change
= requiresNewPassword ? groupOperations
.createModifyGroupLinkPasswordAndRightsChange(
312 GroupLinkPassword
.createNew().serialize(),
313 accessRequired
) : groupOperations
.createChangeJoinByLinkRights(accessRequired
);
314 return commitChange(groupInfoV2
, change
);
317 public GroupChange
joinGroup(
318 GroupMasterKey groupMasterKey
,
319 GroupLinkPassword groupLinkPassword
,
320 DecryptedGroupJoinInfo decryptedGroupJoinInfo
321 ) throws IOException
{
322 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
323 final var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
325 final var selfRecipientId
= this.selfRecipientIdProvider
.getSelfRecipientId();
326 final var profileKeyCredential
= profileKeyCredentialProvider
.getProfileKeyCredential(selfRecipientId
);
327 if (profileKeyCredential
== null) {
328 throw new IOException("Cannot join a V2 group as self does not have a versioned profile");
331 var requestToJoin
= decryptedGroupJoinInfo
.getAddFromInviteLink() == AccessControl
.AccessRequired
.ADMINISTRATOR
;
332 var change
= requestToJoin
333 ? groupOperations
.createGroupJoinRequest(profileKeyCredential
)
334 : groupOperations
.createGroupJoinDirect(profileKeyCredential
);
336 change
.setSourceUuid(UuidUtil
.toByteString(addressResolver
.resolveSignalServiceAddress(selfRecipientId
)
340 return commitChange(groupSecretParams
, decryptedGroupJoinInfo
.getRevision(), change
, groupLinkPassword
);
343 public Pair
<DecryptedGroup
, GroupChange
> acceptInvite(GroupInfoV2 groupInfoV2
) throws IOException
{
344 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
346 final var selfRecipientId
= this.selfRecipientIdProvider
.getSelfRecipientId();
347 final var profileKeyCredential
= profileKeyCredentialProvider
.getProfileKeyCredential(selfRecipientId
);
348 if (profileKeyCredential
== null) {
349 throw new IOException("Cannot join a V2 group as self does not have a versioned profile");
352 final var change
= groupOperations
.createAcceptInviteChange(profileKeyCredential
);
354 final var uuid
= addressResolver
.resolveSignalServiceAddress(selfRecipientId
).getUuid();
355 if (uuid
.isPresent()) {
356 change
.setSourceUuid(UuidUtil
.toByteString(uuid
.get()));
359 return commitChange(groupInfoV2
, change
);
362 public Pair
<DecryptedGroup
, GroupChange
> setMemberAdmin(
363 GroupInfoV2 groupInfoV2
, RecipientId recipientId
, boolean admin
364 ) throws IOException
{
365 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
366 final var address
= addressResolver
.resolveSignalServiceAddress(recipientId
);
367 final var newRole
= admin ? Member
.Role
.ADMINISTRATOR
: Member
.Role
.DEFAULT
;
368 final var change
= groupOperations
.createChangeMemberRole(address
.getUuid().get(), newRole
);
369 return commitChange(groupInfoV2
, change
);
372 public Pair
<DecryptedGroup
, GroupChange
> setMessageExpirationTimer(
373 GroupInfoV2 groupInfoV2
, int messageExpirationTimer
374 ) throws IOException
{
375 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
376 final var change
= groupOperations
.createModifyGroupTimerChange(messageExpirationTimer
);
377 return commitChange(groupInfoV2
, change
);
380 private AccessControl
.AccessRequired
toAccessControl(final GroupLinkState state
) {
383 return AccessControl
.AccessRequired
.UNSATISFIABLE
;
385 return AccessControl
.AccessRequired
.ANY
;
386 case ENABLED_WITH_APPROVAL
:
387 return AccessControl
.AccessRequired
.ADMINISTRATOR
;
389 throw new AssertionError();
393 private GroupsV2Operations
.GroupOperations
getGroupOperations(final GroupInfoV2 groupInfoV2
) {
394 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupInfoV2
.getMasterKey());
395 return groupsV2Operations
.forGroup(groupSecretParams
);
398 private Pair
<DecryptedGroup
, GroupChange
> revokeInvites(
399 GroupInfoV2 groupInfoV2
, Set
<DecryptedPendingMember
> pendingMembers
400 ) throws IOException
{
401 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
402 final var uuidCipherTexts
= pendingMembers
.stream().map(member
-> {
404 return new UuidCiphertext(member
.getUuidCipherText().toByteArray());
405 } catch (InvalidInputException e
) {
406 throw new AssertionError(e
);
408 }).collect(Collectors
.toSet());
409 return commitChange(groupInfoV2
, groupOperations
.createRemoveInvitationChange(uuidCipherTexts
));
412 private Pair
<DecryptedGroup
, GroupChange
> ejectMembers(
413 GroupInfoV2 groupInfoV2
, Set
<UUID
> uuids
414 ) throws IOException
{
415 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
416 return commitChange(groupInfoV2
, groupOperations
.createRemoveMembersChange(uuids
));
419 private Pair
<DecryptedGroup
, GroupChange
> commitChange(
420 GroupInfoV2 groupInfoV2
, GroupChange
.Actions
.Builder change
421 ) throws IOException
{
422 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupInfoV2
.getMasterKey());
423 final var groupOperations
= groupsV2Operations
.forGroup(groupSecretParams
);
424 final var previousGroupState
= groupInfoV2
.getGroup();
425 final var nextRevision
= previousGroupState
.getRevision() + 1;
426 final var changeActions
= change
.setRevision(nextRevision
).build();
427 final DecryptedGroupChange decryptedChange
;
428 final DecryptedGroup decryptedGroupState
;
431 decryptedChange
= groupOperations
.decryptChange(changeActions
,
432 addressResolver
.resolveSignalServiceAddress(selfRecipientIdProvider
.getSelfRecipientId())
435 decryptedGroupState
= DecryptedGroupUtil
.apply(previousGroupState
, decryptedChange
);
436 } catch (VerificationFailedException
| InvalidGroupStateException
| NotAbleToApplyGroupV2ChangeException e
) {
437 throw new IOException(e
);
440 var signedGroupChange
= groupsV2Api
.patchGroup(changeActions
,
441 groupAuthorizationProvider
.getAuthorizationForToday(groupSecretParams
),
444 return new Pair
<>(decryptedGroupState
, signedGroupChange
);
447 private GroupChange
commitChange(
448 GroupSecretParams groupSecretParams
,
450 GroupChange
.Actions
.Builder change
,
451 GroupLinkPassword password
452 ) throws IOException
{
453 final var nextRevision
= currentRevision
+ 1;
454 final var changeActions
= change
.setRevision(nextRevision
).build();
456 return groupsV2Api
.patchGroup(changeActions
,
457 groupAuthorizationProvider
.getAuthorizationForToday(groupSecretParams
),
458 Optional
.fromNullable(password
).transform(GroupLinkPassword
::serialize
));
461 public DecryptedGroup
getUpdatedDecryptedGroup(
462 DecryptedGroup group
, byte[] signedGroupChange
, GroupMasterKey groupMasterKey
465 final var decryptedGroupChange
= getDecryptedGroupChange(signedGroupChange
, groupMasterKey
);
466 if (decryptedGroupChange
== null) {
469 return DecryptedGroupUtil
.apply(group
, decryptedGroupChange
);
470 } catch (NotAbleToApplyGroupV2ChangeException e
) {
475 private DecryptedGroupChange
getDecryptedGroupChange(byte[] signedGroupChange
, GroupMasterKey groupMasterKey
) {
476 if (signedGroupChange
!= null) {
477 var groupOperations
= groupsV2Operations
.forGroup(GroupSecretParams
.deriveFromMasterKey(groupMasterKey
));
480 return groupOperations
.decryptChange(GroupChange
.parseFrom(signedGroupChange
), true).orNull();
481 } catch (VerificationFailedException
| InvalidGroupStateException
| InvalidProtocolBufferException e
) {