1 package org
.asamk
.signal
.manager
.helper
;
3 import com
.google
.protobuf
.ByteString
;
4 import com
.google
.protobuf
.InvalidProtocolBufferException
;
6 import org
.asamk
.signal
.manager
.SignalDependencies
;
7 import org
.asamk
.signal
.manager
.api
.Pair
;
8 import org
.asamk
.signal
.manager
.groups
.GroupLinkPassword
;
9 import org
.asamk
.signal
.manager
.groups
.GroupLinkState
;
10 import org
.asamk
.signal
.manager
.groups
.GroupPermission
;
11 import org
.asamk
.signal
.manager
.groups
.GroupUtils
;
12 import org
.asamk
.signal
.manager
.groups
.NotAGroupMemberException
;
13 import org
.asamk
.signal
.manager
.storage
.groups
.GroupInfoV2
;
14 import org
.asamk
.signal
.manager
.storage
.recipients
.RecipientId
;
15 import org
.asamk
.signal
.manager
.util
.IOUtils
;
16 import org
.asamk
.signal
.manager
.util
.Utils
;
17 import org
.signal
.libsignal
.zkgroup
.InvalidInputException
;
18 import org
.signal
.libsignal
.zkgroup
.VerificationFailedException
;
19 import org
.signal
.libsignal
.zkgroup
.auth
.AuthCredentialWithPniResponse
;
20 import org
.signal
.libsignal
.zkgroup
.groups
.GroupMasterKey
;
21 import org
.signal
.libsignal
.zkgroup
.groups
.GroupSecretParams
;
22 import org
.signal
.libsignal
.zkgroup
.groups
.UuidCiphertext
;
23 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKey
;
24 import org
.signal
.storageservice
.protos
.groups
.AccessControl
;
25 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
26 import org
.signal
.storageservice
.protos
.groups
.Member
;
27 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
28 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroupChange
;
29 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroupJoinInfo
;
30 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedMember
;
31 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedPendingMember
;
32 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedRequestingMember
;
33 import org
.slf4j
.Logger
;
34 import org
.slf4j
.LoggerFactory
;
35 import org
.whispersystems
.signalservice
.api
.groupsv2
.DecryptedGroupUtil
;
36 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupCandidate
;
37 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupHistoryPage
;
38 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
39 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
40 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
41 import org
.whispersystems
.signalservice
.api
.groupsv2
.InvalidGroupStateException
;
42 import org
.whispersystems
.signalservice
.api
.groupsv2
.NotAbleToApplyGroupV2ChangeException
;
43 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
44 import org
.whispersystems
.signalservice
.api
.push
.PNI
;
45 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
;
46 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
47 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NonSuccessfulResponseCodeException
;
48 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
51 import java
.io
.FileInputStream
;
52 import java
.io
.IOException
;
53 import java
.io
.InputStream
;
54 import java
.util
.ArrayList
;
55 import java
.util
.Arrays
;
56 import java
.util
.HashMap
;
57 import java
.util
.List
;
58 import java
.util
.Optional
;
60 import java
.util
.UUID
;
61 import java
.util
.concurrent
.TimeUnit
;
62 import java
.util
.function
.Function
;
63 import java
.util
.stream
.Collectors
;
64 import java
.util
.stream
.Stream
;
68 private final static Logger logger
= LoggerFactory
.getLogger(GroupV2Helper
.class);
70 private final SignalDependencies dependencies
;
71 private final Context context
;
73 private HashMap
<Long
, AuthCredentialWithPniResponse
> groupApiCredentials
;
75 GroupV2Helper(final Context context
) {
76 this.dependencies
= context
.getDependencies();
77 this.context
= context
;
80 DecryptedGroup
getDecryptedGroup(final GroupSecretParams groupSecretParams
) throws NotAGroupMemberException
{
82 final var groupsV2AuthorizationString
= getGroupAuthForToday(groupSecretParams
);
83 return dependencies
.getGroupsV2Api().getGroup(groupSecretParams
, groupsV2AuthorizationString
);
84 } catch (NonSuccessfulResponseCodeException e
) {
85 if (e
.getCode() == 403) {
86 throw new NotAGroupMemberException(GroupUtils
.getGroupIdV2(groupSecretParams
), null);
88 logger
.warn("Failed to retrieve Group V2 info, ignoring: {}", e
.getMessage());
90 } catch (IOException
| VerificationFailedException
| InvalidGroupStateException e
) {
91 logger
.warn("Failed to retrieve Group V2 info, ignoring: {}", e
.getMessage());
96 DecryptedGroupJoinInfo
getDecryptedGroupJoinInfo(
97 GroupMasterKey groupMasterKey
, GroupLinkPassword password
98 ) throws IOException
, GroupLinkNotActiveException
{
99 var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
101 return dependencies
.getGroupsV2Api()
102 .getGroupJoinInfo(groupSecretParams
,
103 Optional
.ofNullable(password
).map(GroupLinkPassword
::serialize
),
104 getGroupAuthForToday(groupSecretParams
));
107 GroupHistoryPage
getDecryptedGroupHistoryPage(
108 final GroupSecretParams groupSecretParams
, int fromRevision
109 ) throws NotAGroupMemberException
{
111 final var groupsV2AuthorizationString
= getGroupAuthForToday(groupSecretParams
);
112 return dependencies
.getGroupsV2Api()
113 .getGroupHistoryPage(groupSecretParams
, fromRevision
, groupsV2AuthorizationString
, false);
114 } catch (NonSuccessfulResponseCodeException e
) {
115 if (e
.getCode() == 403) {
116 throw new NotAGroupMemberException(GroupUtils
.getGroupIdV2(groupSecretParams
), null);
118 logger
.warn("Failed to retrieve Group V2 history, ignoring: {}", e
.getMessage());
120 } catch (IOException
| VerificationFailedException
| InvalidGroupStateException e
) {
121 logger
.warn("Failed to retrieve Group V2 history, ignoring: {}", e
.getMessage());
126 int findRevisionWeWereAdded(DecryptedGroup partialDecryptedGroup
) {
127 ByteString bytes
= UuidUtil
.toByteString(getSelfAci().uuid());
128 for (DecryptedMember decryptedMember
: partialDecryptedGroup
.getMembersList()) {
129 if (decryptedMember
.getUuid().equals(bytes
)) {
130 return decryptedMember
.getJoinedAtRevision();
133 return partialDecryptedGroup
.getRevision();
136 Pair
<GroupInfoV2
, DecryptedGroup
> createGroup(
137 String name
, Set
<RecipientId
> members
, File avatarFile
138 ) throws IOException
{
139 final var avatarBytes
= readAvatarBytes(avatarFile
);
140 final var newGroup
= buildNewGroup(name
, members
, avatarBytes
);
141 if (newGroup
== null) {
145 final var groupSecretParams
= newGroup
.getGroupSecretParams();
147 final GroupsV2AuthorizationString groupAuthForToday
;
148 final DecryptedGroup decryptedGroup
;
150 groupAuthForToday
= getGroupAuthForToday(groupSecretParams
);
151 dependencies
.getGroupsV2Api().putNewGroup(newGroup
, groupAuthForToday
);
152 decryptedGroup
= dependencies
.getGroupsV2Api().getGroup(groupSecretParams
, groupAuthForToday
);
153 } catch (IOException
| VerificationFailedException
| InvalidGroupStateException e
) {
154 logger
.warn("Failed to create V2 group: {}", e
.getMessage());
157 if (decryptedGroup
== null) {
158 logger
.warn("Failed to create V2 group, unknown error!");
162 final var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
163 final var masterKey
= groupSecretParams
.getMasterKey();
164 var g
= new GroupInfoV2(groupId
, masterKey
, context
.getAccount().getRecipientResolver());
166 return new Pair
<>(g
, decryptedGroup
);
169 private byte[] readAvatarBytes(final File avatarFile
) throws IOException
{
170 final byte[] avatarBytes
;
171 try (InputStream avatar
= avatarFile
== null ?
null : new FileInputStream(avatarFile
)) {
172 avatarBytes
= avatar
== null ?
null : IOUtils
.readFully(avatar
);
177 private GroupsV2Operations
.NewGroup
buildNewGroup(
178 String name
, Set
<RecipientId
> members
, byte[] avatar
180 final var profileKeyCredential
= context
.getProfileHelper()
181 .getExpiringProfileKeyCredential(context
.getAccount().getSelfRecipientId());
182 if (profileKeyCredential
== null) {
183 logger
.warn("Cannot create a V2 group as self does not have a versioned profile");
187 final var self
= new GroupCandidate(getSelfAci().uuid(), Optional
.of(profileKeyCredential
));
188 final var memberList
= new ArrayList
<>(members
);
189 final var credentials
= context
.getProfileHelper().getExpiringProfileKeyCredential(memberList
).stream();
190 final var uuids
= memberList
.stream()
191 .map(member
-> context
.getRecipientHelper().resolveSignalServiceAddress(member
).getServiceId().uuid());
192 var candidates
= Utils
.zip(uuids
,
194 (uuid
, credential
) -> new GroupCandidate(uuid
, Optional
.ofNullable(credential
)))
195 .collect(Collectors
.toSet());
197 final var groupSecretParams
= GroupSecretParams
.generate();
198 return dependencies
.getGroupsV2Operations()
199 .createNewGroup(groupSecretParams
,
201 Optional
.ofNullable(avatar
),
208 Pair
<DecryptedGroup
, GroupChange
> updateGroup(
209 GroupInfoV2 groupInfoV2
, String name
, String description
, File avatarFile
210 ) throws IOException
{
211 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupInfoV2
.getMasterKey());
212 var groupOperations
= dependencies
.getGroupsV2Operations().forGroup(groupSecretParams
);
214 var change
= name
!= null ? groupOperations
.createModifyGroupTitle(name
) : GroupChange
.Actions
.newBuilder();
216 if (description
!= null) {
217 change
.setModifyDescription(groupOperations
.createModifyGroupDescriptionAction(description
));
220 if (avatarFile
!= null) {
221 final var avatarBytes
= readAvatarBytes(avatarFile
);
222 var avatarCdnKey
= dependencies
.getGroupsV2Api()
223 .uploadAvatar(avatarBytes
, groupSecretParams
, getGroupAuthForToday(groupSecretParams
));
224 change
.setModifyAvatar(GroupChange
.Actions
.ModifyAvatarAction
.newBuilder().setAvatar(avatarCdnKey
));
227 change
.setSourceUuid(getSelfAci().toByteString());
229 return commitChange(groupInfoV2
, change
);
232 Pair
<DecryptedGroup
, GroupChange
> addMembers(
233 GroupInfoV2 groupInfoV2
, Set
<RecipientId
> newMembers
234 ) throws IOException
{
235 GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
237 final var memberList
= new ArrayList
<>(newMembers
);
238 final var credentials
= context
.getProfileHelper().getExpiringProfileKeyCredential(memberList
).stream();
239 final var uuids
= memberList
.stream()
240 .map(member
-> context
.getRecipientHelper().resolveSignalServiceAddress(member
).getServiceId().uuid());
241 var candidates
= Utils
.zip(uuids
,
243 (uuid
, credential
) -> new GroupCandidate(uuid
, Optional
.ofNullable(credential
)))
244 .collect(Collectors
.toSet());
245 final var bannedUuids
= groupInfoV2
.getBannedMembers()
247 .map(member
-> context
.getRecipientHelper().resolveSignalServiceAddress(member
).getServiceId().uuid())
248 .collect(Collectors
.toSet());
250 final var aci
= getSelfAci();
251 final var change
= groupOperations
.createModifyGroupMembershipChange(candidates
, bannedUuids
, aci
.uuid());
253 change
.setSourceUuid(getSelfAci().toByteString());
255 return commitChange(groupInfoV2
, change
);
258 Pair
<DecryptedGroup
, GroupChange
> leaveGroup(
259 GroupInfoV2 groupInfoV2
, Set
<RecipientId
> membersToMakeAdmin
260 ) throws IOException
{
261 var pendingMembersList
= groupInfoV2
.getGroup().getPendingMembersList();
262 final var selfAci
= getSelfAci();
263 var selfPendingMember
= DecryptedGroupUtil
.findPendingByUuid(pendingMembersList
, selfAci
.uuid());
265 if (selfPendingMember
.isPresent()) {
266 return revokeInvites(groupInfoV2
, Set
.of(selfPendingMember
.get()));
269 final var adminUuids
= membersToMakeAdmin
.stream()
270 .map(context
.getRecipientHelper()::resolveSignalServiceAddress
)
271 .map(SignalServiceAddress
::getServiceId
)
272 .map(ServiceId
::uuid
)
274 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
275 return commitChange(groupInfoV2
,
276 groupOperations
.createLeaveAndPromoteMembersToAdmin(selfAci
.uuid(), adminUuids
));
279 Pair
<DecryptedGroup
, GroupChange
> removeMembers(
280 GroupInfoV2 groupInfoV2
, Set
<RecipientId
> members
281 ) throws IOException
{
282 final var memberUuids
= members
.stream()
283 .map(context
.getRecipientHelper()::resolveSignalServiceAddress
)
284 .map(SignalServiceAddress
::getServiceId
)
285 .map(ServiceId
::uuid
)
286 .collect(Collectors
.toSet());
287 return ejectMembers(groupInfoV2
, memberUuids
);
290 Pair
<DecryptedGroup
, GroupChange
> refuseJoinRequestMembers(
291 GroupInfoV2 groupInfoV2
, Set
<RecipientId
> members
292 ) throws IOException
{
293 final var memberUuids
= members
.stream()
294 .map(context
.getRecipientHelper()::resolveSignalServiceAddress
)
295 .map(SignalServiceAddress
::getServiceId
)
296 .map(ServiceId
::uuid
)
297 .collect(Collectors
.toSet());
298 return refuseJoinRequest(groupInfoV2
, memberUuids
);
301 Pair
<DecryptedGroup
, GroupChange
> revokeInvitedMembers(
302 GroupInfoV2 groupInfoV2
, Set
<RecipientId
> members
303 ) throws IOException
{
304 var pendingMembersList
= groupInfoV2
.getGroup().getPendingMembersList();
305 final var memberUuids
= members
.stream()
306 .map(context
.getRecipientHelper()::resolveSignalServiceAddress
)
307 .map(SignalServiceAddress
::getServiceId
)
308 .map(ServiceId
::uuid
)
309 .map(uuid
-> DecryptedGroupUtil
.findPendingByUuid(pendingMembersList
, uuid
))
310 .filter(Optional
::isPresent
)
312 .collect(Collectors
.toSet());
313 return revokeInvites(groupInfoV2
, memberUuids
);
316 Pair
<DecryptedGroup
, GroupChange
> banMembers(
317 GroupInfoV2 groupInfoV2
, Set
<RecipientId
> block
318 ) throws IOException
{
319 GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
321 final var uuids
= block
.stream()
322 .map(member
-> context
.getRecipientHelper().resolveSignalServiceAddress(member
).getServiceId().uuid())
323 .collect(Collectors
.toSet());
325 final var change
= groupOperations
.createBanUuidsChange(uuids
,
327 groupInfoV2
.getGroup().getBannedMembersList());
329 change
.setSourceUuid(getSelfAci().toByteString());
331 return commitChange(groupInfoV2
, change
);
334 Pair
<DecryptedGroup
, GroupChange
> unbanMembers(
335 GroupInfoV2 groupInfoV2
, Set
<RecipientId
> block
336 ) throws IOException
{
337 GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
339 final var uuids
= block
.stream()
340 .map(member
-> context
.getRecipientHelper().resolveSignalServiceAddress(member
).getServiceId().uuid())
341 .collect(Collectors
.toSet());
343 final var change
= groupOperations
.createUnbanUuidsChange(uuids
);
345 change
.setSourceUuid(getSelfAci().toByteString());
347 return commitChange(groupInfoV2
, change
);
350 Pair
<DecryptedGroup
, GroupChange
> resetGroupLinkPassword(GroupInfoV2 groupInfoV2
) throws IOException
{
351 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
352 final var newGroupLinkPassword
= GroupLinkPassword
.createNew().serialize();
353 final var change
= groupOperations
.createModifyGroupLinkPasswordChange(newGroupLinkPassword
);
354 return commitChange(groupInfoV2
, change
);
357 Pair
<DecryptedGroup
, GroupChange
> setGroupLinkState(
358 GroupInfoV2 groupInfoV2
, GroupLinkState state
359 ) throws IOException
{
360 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
362 final var accessRequired
= toAccessControl(state
);
363 final var requiresNewPassword
= state
!= GroupLinkState
.DISABLED
&& groupInfoV2
.getGroup()
364 .getInviteLinkPassword()
367 final var change
= requiresNewPassword ? groupOperations
.createModifyGroupLinkPasswordAndRightsChange(
368 GroupLinkPassword
.createNew().serialize(),
369 accessRequired
) : groupOperations
.createChangeJoinByLinkRights(accessRequired
);
370 return commitChange(groupInfoV2
, change
);
373 Pair
<DecryptedGroup
, GroupChange
> setEditDetailsPermission(
374 GroupInfoV2 groupInfoV2
, GroupPermission permission
375 ) throws IOException
{
376 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
378 final var accessRequired
= toAccessControl(permission
);
379 final var change
= groupOperations
.createChangeAttributesRights(accessRequired
);
380 return commitChange(groupInfoV2
, change
);
383 Pair
<DecryptedGroup
, GroupChange
> setAddMemberPermission(
384 GroupInfoV2 groupInfoV2
, GroupPermission permission
385 ) throws IOException
{
386 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
388 final var accessRequired
= toAccessControl(permission
);
389 final var change
= groupOperations
.createChangeMembershipRights(accessRequired
);
390 return commitChange(groupInfoV2
, change
);
393 Pair
<DecryptedGroup
, GroupChange
> updateSelfProfileKey(GroupInfoV2 groupInfoV2
) throws IOException
{
394 Optional
<DecryptedMember
> selfInGroup
= groupInfoV2
.getGroup() == null
396 : DecryptedGroupUtil
.findMemberByUuid(groupInfoV2
.getGroup().getMembersList(), getSelfAci().uuid());
397 if (selfInGroup
.isEmpty()) {
398 logger
.trace("Not updating group, self not in group " + groupInfoV2
.getGroupId().toBase64());
402 final var profileKey
= context
.getAccount().getProfileKey();
403 if (Arrays
.equals(profileKey
.serialize(), selfInGroup
.get().getProfileKey().toByteArray())) {
404 logger
.trace("Not updating group, own Profile Key is already up to date in group "
405 + groupInfoV2
.getGroupId().toBase64());
408 logger
.debug("Updating own profile key in group " + groupInfoV2
.getGroupId().toBase64());
410 final var selfRecipientId
= context
.getAccount().getSelfRecipientId();
411 final var profileKeyCredential
= context
.getProfileHelper().getExpiringProfileKeyCredential(selfRecipientId
);
412 if (profileKeyCredential
== null) {
413 logger
.trace("Cannot update profile key as self does not have a versioned profile");
417 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
418 final var change
= groupOperations
.createUpdateProfileKeyCredentialChange(profileKeyCredential
);
419 change
.setSourceUuid(getSelfAci().toByteString());
420 return commitChange(groupInfoV2
, change
);
423 GroupChange
joinGroup(
424 GroupMasterKey groupMasterKey
,
425 GroupLinkPassword groupLinkPassword
,
426 DecryptedGroupJoinInfo decryptedGroupJoinInfo
427 ) throws IOException
{
428 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
429 final var groupOperations
= dependencies
.getGroupsV2Operations().forGroup(groupSecretParams
);
431 final var selfRecipientId
= context
.getAccount().getSelfRecipientId();
432 final var profileKeyCredential
= context
.getProfileHelper().getExpiringProfileKeyCredential(selfRecipientId
);
433 if (profileKeyCredential
== null) {
434 throw new IOException("Cannot join a V2 group as self does not have a versioned profile");
437 var requestToJoin
= decryptedGroupJoinInfo
.getAddFromInviteLink() == AccessControl
.AccessRequired
.ADMINISTRATOR
;
438 var change
= requestToJoin
439 ? groupOperations
.createGroupJoinRequest(profileKeyCredential
)
440 : groupOperations
.createGroupJoinDirect(profileKeyCredential
);
442 change
.setSourceUuid(context
.getRecipientHelper()
443 .resolveSignalServiceAddress(selfRecipientId
)
447 return commitChange(groupSecretParams
, decryptedGroupJoinInfo
.getRevision(), change
, groupLinkPassword
);
450 Pair
<DecryptedGroup
, GroupChange
> acceptInvite(GroupInfoV2 groupInfoV2
) throws IOException
{
451 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
453 final var selfRecipientId
= context
.getAccount().getSelfRecipientId();
454 final var profileKeyCredential
= context
.getProfileHelper().getExpiringProfileKeyCredential(selfRecipientId
);
455 if (profileKeyCredential
== null) {
456 throw new IOException("Cannot join a V2 group as self does not have a versioned profile");
459 final var change
= groupOperations
.createAcceptInviteChange(profileKeyCredential
);
461 final var aci
= context
.getRecipientHelper().resolveSignalServiceAddress(selfRecipientId
).getServiceId();
462 change
.setSourceUuid(aci
.toByteString());
464 return commitChange(groupInfoV2
, change
);
467 Pair
<DecryptedGroup
, GroupChange
> setMemberAdmin(
468 GroupInfoV2 groupInfoV2
, RecipientId recipientId
, boolean admin
469 ) throws IOException
{
470 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
471 final var address
= context
.getRecipientHelper().resolveSignalServiceAddress(recipientId
);
472 final var newRole
= admin ? Member
.Role
.ADMINISTRATOR
: Member
.Role
.DEFAULT
;
473 final var change
= groupOperations
.createChangeMemberRole(address
.getServiceId().uuid(), newRole
);
474 return commitChange(groupInfoV2
, change
);
477 Pair
<DecryptedGroup
, GroupChange
> setMessageExpirationTimer(
478 GroupInfoV2 groupInfoV2
, int messageExpirationTimer
479 ) throws IOException
{
480 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
481 final var change
= groupOperations
.createModifyGroupTimerChange(messageExpirationTimer
);
482 return commitChange(groupInfoV2
, change
);
485 Pair
<DecryptedGroup
, GroupChange
> setIsAnnouncementGroup(
486 GroupInfoV2 groupInfoV2
, boolean isAnnouncementGroup
487 ) throws IOException
{
488 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
489 final var change
= groupOperations
.createAnnouncementGroupChange(isAnnouncementGroup
);
490 return commitChange(groupInfoV2
, change
);
493 private AccessControl
.AccessRequired
toAccessControl(final GroupLinkState state
) {
494 return switch (state
) {
495 case DISABLED
-> AccessControl
.AccessRequired
.UNSATISFIABLE
;
496 case ENABLED
-> AccessControl
.AccessRequired
.ANY
;
497 case ENABLED_WITH_APPROVAL
-> AccessControl
.AccessRequired
.ADMINISTRATOR
;
501 private AccessControl
.AccessRequired
toAccessControl(final GroupPermission permission
) {
502 return switch (permission
) {
503 case EVERY_MEMBER
-> AccessControl
.AccessRequired
.MEMBER
;
504 case ONLY_ADMINS
-> AccessControl
.AccessRequired
.ADMINISTRATOR
;
508 private GroupsV2Operations
.GroupOperations
getGroupOperations(final GroupInfoV2 groupInfoV2
) {
509 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupInfoV2
.getMasterKey());
510 return dependencies
.getGroupsV2Operations().forGroup(groupSecretParams
);
513 private Pair
<DecryptedGroup
, GroupChange
> revokeInvites(
514 GroupInfoV2 groupInfoV2
, Set
<DecryptedPendingMember
> pendingMembers
515 ) throws IOException
{
516 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
517 final var uuidCipherTexts
= pendingMembers
.stream().map(member
-> {
519 return new UuidCiphertext(member
.getUuidCipherText().toByteArray());
520 } catch (InvalidInputException e
) {
521 throw new AssertionError(e
);
523 }).collect(Collectors
.toSet());
524 return commitChange(groupInfoV2
, groupOperations
.createRemoveInvitationChange(uuidCipherTexts
));
527 private Pair
<DecryptedGroup
, GroupChange
> refuseJoinRequest(
528 GroupInfoV2 groupInfoV2
, Set
<UUID
> uuids
529 ) throws IOException
{
530 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
531 return commitChange(groupInfoV2
, groupOperations
.createRefuseGroupJoinRequest(uuids
, false, List
.of()));
534 private Pair
<DecryptedGroup
, GroupChange
> ejectMembers(
535 GroupInfoV2 groupInfoV2
, Set
<UUID
> uuids
536 ) throws IOException
{
537 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
538 return commitChange(groupInfoV2
, groupOperations
.createRemoveMembersChange(uuids
, false, List
.of()));
541 private Pair
<DecryptedGroup
, GroupChange
> commitChange(
542 GroupInfoV2 groupInfoV2
, GroupChange
.Actions
.Builder change
543 ) throws IOException
{
544 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupInfoV2
.getMasterKey());
545 final var groupOperations
= dependencies
.getGroupsV2Operations().forGroup(groupSecretParams
);
546 final var previousGroupState
= groupInfoV2
.getGroup();
547 final var nextRevision
= previousGroupState
.getRevision() + 1;
548 final var changeActions
= change
.setRevision(nextRevision
).build();
549 final DecryptedGroupChange decryptedChange
;
550 final DecryptedGroup decryptedGroupState
;
553 decryptedChange
= groupOperations
.decryptChange(changeActions
, getSelfAci().uuid());
554 decryptedGroupState
= DecryptedGroupUtil
.apply(previousGroupState
, decryptedChange
);
555 } catch (VerificationFailedException
| InvalidGroupStateException
| NotAbleToApplyGroupV2ChangeException e
) {
556 throw new IOException(e
);
559 var signedGroupChange
= dependencies
.getGroupsV2Api()
560 .patchGroup(changeActions
, getGroupAuthForToday(groupSecretParams
), Optional
.empty());
562 return new Pair
<>(decryptedGroupState
, signedGroupChange
);
565 private GroupChange
commitChange(
566 GroupSecretParams groupSecretParams
,
568 GroupChange
.Actions
.Builder change
,
569 GroupLinkPassword password
570 ) throws IOException
{
571 final var nextRevision
= currentRevision
+ 1;
572 final var changeActions
= change
.setRevision(nextRevision
).build();
574 return dependencies
.getGroupsV2Api()
575 .patchGroup(changeActions
,
576 getGroupAuthForToday(groupSecretParams
),
577 Optional
.ofNullable(password
).map(GroupLinkPassword
::serialize
));
580 Pair
<ServiceId
, ProfileKey
> getAuthoritativeProfileKeyFromChange(final DecryptedGroupChange change
) {
581 UUID editor
= UuidUtil
.fromByteStringOrNull(change
.getEditor());
582 final var editorProfileKeyBytes
= Stream
.concat(Stream
.of(change
.getNewMembersList().stream(),
583 change
.getPromotePendingMembersList().stream(),
584 change
.getModifiedProfileKeysList().stream())
585 .flatMap(Function
.identity())
586 .filter(m
-> UuidUtil
.fromByteString(m
.getUuid()).equals(editor
))
587 .map(DecryptedMember
::getProfileKey
),
588 change
.getNewRequestingMembersList()
590 .filter(m
-> UuidUtil
.fromByteString(m
.getUuid()).equals(editor
))
591 .map(DecryptedRequestingMember
::getProfileKey
)).findFirst();
593 if (editorProfileKeyBytes
.isEmpty()) {
597 ProfileKey profileKey
;
599 profileKey
= new ProfileKey(editorProfileKeyBytes
.get().toByteArray());
600 } catch (InvalidInputException e
) {
601 logger
.debug("Bad profile key in group");
605 return new Pair
<>(ServiceId
.from(editor
), profileKey
);
608 DecryptedGroup
getUpdatedDecryptedGroup(DecryptedGroup group
, DecryptedGroupChange decryptedGroupChange
) {
610 return DecryptedGroupUtil
.apply(group
, decryptedGroupChange
);
611 } catch (NotAbleToApplyGroupV2ChangeException e
) {
616 DecryptedGroupChange
getDecryptedGroupChange(byte[] signedGroupChange
, GroupMasterKey groupMasterKey
) {
617 if (signedGroupChange
!= null) {
618 var groupOperations
= dependencies
.getGroupsV2Operations()
619 .forGroup(GroupSecretParams
.deriveFromMasterKey(groupMasterKey
));
622 return groupOperations
.decryptChange(GroupChange
.parseFrom(signedGroupChange
), true).orElse(null);
623 } catch (VerificationFailedException
| InvalidGroupStateException
| InvalidProtocolBufferException e
) {
631 private static long currentDaySeconds() {
632 return TimeUnit
.DAYS
.toSeconds(TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis()));
635 private GroupsV2AuthorizationString
getGroupAuthForToday(
636 final GroupSecretParams groupSecretParams
637 ) throws IOException
{
638 final var todaySeconds
= currentDaySeconds();
639 if (groupApiCredentials
== null || !groupApiCredentials
.containsKey(todaySeconds
)) {
640 // Returns credentials for the next 7 days
641 groupApiCredentials
= dependencies
.getGroupsV2Api().getCredentials(todaySeconds
);
642 // TODO cache credentials on disk until they expire
645 return getAuthorizationString(groupSecretParams
, todaySeconds
);
646 } catch (VerificationFailedException e
) {
647 logger
.debug("Group api credentials invalid, renewing and trying again.");
648 groupApiCredentials
.clear();
651 groupApiCredentials
= dependencies
.getGroupsV2Api().getCredentials(todaySeconds
);
653 return getAuthorizationString(groupSecretParams
, todaySeconds
);
654 } catch (VerificationFailedException e
) {
655 throw new IOException(e
);
659 private GroupsV2AuthorizationString
getAuthorizationString(
660 final GroupSecretParams groupSecretParams
, final long todaySeconds
661 ) throws VerificationFailedException
{
662 var authCredentialResponse
= groupApiCredentials
.get(todaySeconds
);
663 final var aci
= getSelfAci();
664 final var pni
= getSelfPni();
665 return dependencies
.getGroupsV2Api()
666 .getGroupsV2AuthorizationString(aci
, pni
, todaySeconds
, groupSecretParams
, authCredentialResponse
);
669 private ACI
getSelfAci() {
670 return context
.getAccount().getAci();
673 private PNI
getSelfPni() {
674 return context
.getAccount().getPni();