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
.Utils
;
16 import org
.signal
.libsignal
.zkgroup
.InvalidInputException
;
17 import org
.signal
.libsignal
.zkgroup
.VerificationFailedException
;
18 import org
.signal
.libsignal
.zkgroup
.auth
.AuthCredentialWithPniResponse
;
19 import org
.signal
.libsignal
.zkgroup
.groups
.GroupMasterKey
;
20 import org
.signal
.libsignal
.zkgroup
.groups
.GroupSecretParams
;
21 import org
.signal
.libsignal
.zkgroup
.groups
.UuidCiphertext
;
22 import org
.signal
.libsignal
.zkgroup
.profiles
.ProfileKey
;
23 import org
.signal
.storageservice
.protos
.groups
.AccessControl
;
24 import org
.signal
.storageservice
.protos
.groups
.GroupChange
;
25 import org
.signal
.storageservice
.protos
.groups
.Member
;
26 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroup
;
27 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroupChange
;
28 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedGroupJoinInfo
;
29 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedMember
;
30 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedPendingMember
;
31 import org
.signal
.storageservice
.protos
.groups
.local
.DecryptedRequestingMember
;
32 import org
.slf4j
.Logger
;
33 import org
.slf4j
.LoggerFactory
;
34 import org
.whispersystems
.signalservice
.api
.groupsv2
.DecryptedGroupUtil
;
35 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupCandidate
;
36 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupHistoryPage
;
37 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupLinkNotActiveException
;
38 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2AuthorizationString
;
39 import org
.whispersystems
.signalservice
.api
.groupsv2
.GroupsV2Operations
;
40 import org
.whispersystems
.signalservice
.api
.groupsv2
.InvalidGroupStateException
;
41 import org
.whispersystems
.signalservice
.api
.groupsv2
.NotAbleToApplyGroupV2ChangeException
;
42 import org
.whispersystems
.signalservice
.api
.push
.ACI
;
43 import org
.whispersystems
.signalservice
.api
.push
.PNI
;
44 import org
.whispersystems
.signalservice
.api
.push
.ServiceId
;
45 import org
.whispersystems
.signalservice
.api
.push
.SignalServiceAddress
;
46 import org
.whispersystems
.signalservice
.api
.push
.exceptions
.NonSuccessfulResponseCodeException
;
47 import org
.whispersystems
.signalservice
.api
.util
.UuidUtil
;
49 import java
.io
.IOException
;
50 import java
.util
.ArrayList
;
51 import java
.util
.Arrays
;
52 import java
.util
.HashMap
;
53 import java
.util
.List
;
54 import java
.util
.Optional
;
56 import java
.util
.UUID
;
57 import java
.util
.concurrent
.TimeUnit
;
58 import java
.util
.function
.Function
;
59 import java
.util
.stream
.Collectors
;
60 import java
.util
.stream
.Stream
;
64 private final static Logger logger
= LoggerFactory
.getLogger(GroupV2Helper
.class);
66 private final SignalDependencies dependencies
;
67 private final Context context
;
69 private HashMap
<Long
, AuthCredentialWithPniResponse
> groupApiCredentials
;
71 GroupV2Helper(final Context context
) {
72 this.dependencies
= context
.getDependencies();
73 this.context
= context
;
76 void clearAuthCredentialCache() {
77 groupApiCredentials
= null;
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
, byte[] avatarFile
139 final var newGroup
= buildNewGroup(name
, members
, avatarFile
);
140 if (newGroup
== null) {
144 final var groupSecretParams
= newGroup
.getGroupSecretParams();
146 final GroupsV2AuthorizationString groupAuthForToday
;
147 final DecryptedGroup decryptedGroup
;
149 groupAuthForToday
= getGroupAuthForToday(groupSecretParams
);
150 dependencies
.getGroupsV2Api().putNewGroup(newGroup
, groupAuthForToday
);
151 decryptedGroup
= dependencies
.getGroupsV2Api().getGroup(groupSecretParams
, groupAuthForToday
);
152 } catch (IOException
| VerificationFailedException
| InvalidGroupStateException e
) {
153 logger
.warn("Failed to create V2 group: {}", e
.getMessage());
156 if (decryptedGroup
== null) {
157 logger
.warn("Failed to create V2 group, unknown error!");
161 final var groupId
= GroupUtils
.getGroupIdV2(groupSecretParams
);
162 final var masterKey
= groupSecretParams
.getMasterKey();
163 var g
= new GroupInfoV2(groupId
, masterKey
, context
.getAccount().getRecipientResolver());
165 return new Pair
<>(g
, decryptedGroup
);
168 private GroupsV2Operations
.NewGroup
buildNewGroup(
169 String name
, Set
<RecipientId
> members
, byte[] avatar
171 final var profileKeyCredential
= context
.getProfileHelper()
172 .getExpiringProfileKeyCredential(context
.getAccount().getSelfRecipientId());
173 if (profileKeyCredential
== null) {
174 logger
.warn("Cannot create a V2 group as self does not have a versioned profile");
178 final var self
= new GroupCandidate(getSelfAci().uuid(), Optional
.of(profileKeyCredential
));
179 final var memberList
= new ArrayList
<>(members
);
180 final var credentials
= context
.getProfileHelper().getExpiringProfileKeyCredential(memberList
).stream();
181 final var uuids
= memberList
.stream()
182 .map(member
-> context
.getRecipientHelper().resolveSignalServiceAddress(member
).getServiceId().uuid());
183 var candidates
= Utils
.zip(uuids
,
185 (uuid
, credential
) -> new GroupCandidate(uuid
, Optional
.ofNullable(credential
)))
186 .collect(Collectors
.toSet());
188 final var groupSecretParams
= GroupSecretParams
.generate();
189 return dependencies
.getGroupsV2Operations()
190 .createNewGroup(groupSecretParams
,
192 Optional
.ofNullable(avatar
),
199 Pair
<DecryptedGroup
, GroupChange
> updateGroup(
200 GroupInfoV2 groupInfoV2
, String name
, String description
, byte[] avatarFile
201 ) throws IOException
{
202 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupInfoV2
.getMasterKey());
203 var groupOperations
= dependencies
.getGroupsV2Operations().forGroup(groupSecretParams
);
205 var change
= name
!= null ? groupOperations
.createModifyGroupTitle(name
) : GroupChange
.Actions
.newBuilder();
207 if (description
!= null) {
208 change
.setModifyDescription(groupOperations
.createModifyGroupDescriptionAction(description
));
211 if (avatarFile
!= null) {
212 var avatarCdnKey
= dependencies
.getGroupsV2Api()
213 .uploadAvatar(avatarFile
, groupSecretParams
, getGroupAuthForToday(groupSecretParams
));
214 change
.setModifyAvatar(GroupChange
.Actions
.ModifyAvatarAction
.newBuilder().setAvatar(avatarCdnKey
));
217 change
.setSourceUuid(getSelfAci().toByteString());
219 return commitChange(groupInfoV2
, change
);
222 Pair
<DecryptedGroup
, GroupChange
> addMembers(
223 GroupInfoV2 groupInfoV2
, Set
<RecipientId
> newMembers
224 ) throws IOException
{
225 GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
227 final var memberList
= new ArrayList
<>(newMembers
);
228 final var credentials
= context
.getProfileHelper().getExpiringProfileKeyCredential(memberList
).stream();
229 final var uuids
= memberList
.stream()
230 .map(member
-> context
.getRecipientHelper().resolveSignalServiceAddress(member
).getServiceId().uuid());
231 var candidates
= Utils
.zip(uuids
,
233 (uuid
, credential
) -> new GroupCandidate(uuid
, Optional
.ofNullable(credential
)))
234 .collect(Collectors
.toSet());
235 final var bannedUuids
= groupInfoV2
.getBannedMembers()
237 .map(member
-> context
.getRecipientHelper().resolveSignalServiceAddress(member
).getServiceId().uuid())
238 .collect(Collectors
.toSet());
240 final var aci
= getSelfAci();
241 final var change
= groupOperations
.createModifyGroupMembershipChange(candidates
, bannedUuids
, aci
.uuid());
243 change
.setSourceUuid(getSelfAci().toByteString());
245 return commitChange(groupInfoV2
, change
);
248 Pair
<DecryptedGroup
, GroupChange
> leaveGroup(
249 GroupInfoV2 groupInfoV2
, Set
<RecipientId
> membersToMakeAdmin
250 ) throws IOException
{
251 var pendingMembersList
= groupInfoV2
.getGroup().getPendingMembersList();
252 final var selfAci
= getSelfAci();
253 var selfPendingMember
= DecryptedGroupUtil
.findPendingByUuid(pendingMembersList
, selfAci
.uuid());
255 if (selfPendingMember
.isPresent()) {
256 return revokeInvites(groupInfoV2
, Set
.of(selfPendingMember
.get()));
259 final var adminUuids
= membersToMakeAdmin
.stream()
260 .map(context
.getRecipientHelper()::resolveSignalServiceAddress
)
261 .map(SignalServiceAddress
::getServiceId
)
262 .map(ServiceId
::uuid
)
264 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
265 return commitChange(groupInfoV2
,
266 groupOperations
.createLeaveAndPromoteMembersToAdmin(selfAci
.uuid(), adminUuids
));
269 Pair
<DecryptedGroup
, GroupChange
> removeMembers(
270 GroupInfoV2 groupInfoV2
, Set
<RecipientId
> members
271 ) throws IOException
{
272 final var memberUuids
= members
.stream()
273 .map(context
.getRecipientHelper()::resolveSignalServiceAddress
)
274 .map(SignalServiceAddress
::getServiceId
)
275 .map(ServiceId
::uuid
)
276 .collect(Collectors
.toSet());
277 return ejectMembers(groupInfoV2
, memberUuids
);
280 Pair
<DecryptedGroup
, GroupChange
> approveJoinRequestMembers(
281 GroupInfoV2 groupInfoV2
, Set
<RecipientId
> members
282 ) throws IOException
{
283 final var memberUuids
= members
.stream()
284 .map(context
.getRecipientHelper()::resolveSignalServiceAddress
)
285 .map(SignalServiceAddress
::getServiceId
)
286 .map(ServiceId
::uuid
)
287 .collect(Collectors
.toSet());
288 return approveJoinRequest(groupInfoV2
, memberUuids
);
291 Pair
<DecryptedGroup
, GroupChange
> refuseJoinRequestMembers(
292 GroupInfoV2 groupInfoV2
, Set
<RecipientId
> members
293 ) throws IOException
{
294 final var memberUuids
= members
.stream()
295 .map(context
.getRecipientHelper()::resolveSignalServiceAddress
)
296 .map(SignalServiceAddress
::getServiceId
)
297 .map(ServiceId
::uuid
)
298 .collect(Collectors
.toSet());
299 return refuseJoinRequest(groupInfoV2
, memberUuids
);
302 Pair
<DecryptedGroup
, GroupChange
> revokeInvitedMembers(
303 GroupInfoV2 groupInfoV2
, Set
<RecipientId
> members
304 ) throws IOException
{
305 var pendingMembersList
= groupInfoV2
.getGroup().getPendingMembersList();
306 final var memberUuids
= members
.stream()
307 .map(context
.getRecipientHelper()::resolveSignalServiceAddress
)
308 .map(SignalServiceAddress
::getServiceId
)
309 .map(ServiceId
::uuid
)
310 .map(uuid
-> DecryptedGroupUtil
.findPendingByUuid(pendingMembersList
, uuid
))
311 .filter(Optional
::isPresent
)
313 .collect(Collectors
.toSet());
314 return revokeInvites(groupInfoV2
, memberUuids
);
317 Pair
<DecryptedGroup
, GroupChange
> banMembers(
318 GroupInfoV2 groupInfoV2
, Set
<RecipientId
> block
319 ) throws IOException
{
320 GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
322 final var uuids
= block
.stream()
323 .map(member
-> context
.getRecipientHelper().resolveSignalServiceAddress(member
).getServiceId().uuid())
324 .collect(Collectors
.toSet());
326 final var change
= groupOperations
.createBanUuidsChange(uuids
,
328 groupInfoV2
.getGroup().getBannedMembersList());
330 change
.setSourceUuid(getSelfAci().toByteString());
332 return commitChange(groupInfoV2
, change
);
335 Pair
<DecryptedGroup
, GroupChange
> unbanMembers(
336 GroupInfoV2 groupInfoV2
, Set
<RecipientId
> block
337 ) throws IOException
{
338 GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
340 final var uuids
= block
.stream()
341 .map(member
-> context
.getRecipientHelper().resolveSignalServiceAddress(member
).getServiceId().uuid())
342 .collect(Collectors
.toSet());
344 final var change
= groupOperations
.createUnbanUuidsChange(uuids
);
346 change
.setSourceUuid(getSelfAci().toByteString());
348 return commitChange(groupInfoV2
, change
);
351 Pair
<DecryptedGroup
, GroupChange
> resetGroupLinkPassword(GroupInfoV2 groupInfoV2
) throws IOException
{
352 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
353 final var newGroupLinkPassword
= GroupLinkPassword
.createNew().serialize();
354 final var change
= groupOperations
.createModifyGroupLinkPasswordChange(newGroupLinkPassword
);
355 return commitChange(groupInfoV2
, change
);
358 Pair
<DecryptedGroup
, GroupChange
> setGroupLinkState(
359 GroupInfoV2 groupInfoV2
, GroupLinkState state
360 ) throws IOException
{
361 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
363 final var accessRequired
= toAccessControl(state
);
364 final var requiresNewPassword
= state
!= GroupLinkState
.DISABLED
&& groupInfoV2
.getGroup()
365 .getInviteLinkPassword()
368 final var change
= requiresNewPassword ? groupOperations
.createModifyGroupLinkPasswordAndRightsChange(
369 GroupLinkPassword
.createNew().serialize(),
370 accessRequired
) : groupOperations
.createChangeJoinByLinkRights(accessRequired
);
371 return commitChange(groupInfoV2
, change
);
374 Pair
<DecryptedGroup
, GroupChange
> setEditDetailsPermission(
375 GroupInfoV2 groupInfoV2
, GroupPermission permission
376 ) throws IOException
{
377 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
379 final var accessRequired
= toAccessControl(permission
);
380 final var change
= groupOperations
.createChangeAttributesRights(accessRequired
);
381 return commitChange(groupInfoV2
, change
);
384 Pair
<DecryptedGroup
, GroupChange
> setAddMemberPermission(
385 GroupInfoV2 groupInfoV2
, GroupPermission permission
386 ) throws IOException
{
387 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
389 final var accessRequired
= toAccessControl(permission
);
390 final var change
= groupOperations
.createChangeMembershipRights(accessRequired
);
391 return commitChange(groupInfoV2
, change
);
394 Pair
<DecryptedGroup
, GroupChange
> updateSelfProfileKey(GroupInfoV2 groupInfoV2
) throws IOException
{
395 Optional
<DecryptedMember
> selfInGroup
= groupInfoV2
.getGroup() == null
397 : DecryptedGroupUtil
.findMemberByUuid(groupInfoV2
.getGroup().getMembersList(), getSelfAci().uuid());
398 if (selfInGroup
.isEmpty()) {
399 logger
.trace("Not updating group, self not in group " + groupInfoV2
.getGroupId().toBase64());
403 final var profileKey
= context
.getAccount().getProfileKey();
404 if (Arrays
.equals(profileKey
.serialize(), selfInGroup
.get().getProfileKey().toByteArray())) {
405 logger
.trace("Not updating group, own Profile Key is already up to date in group "
406 + groupInfoV2
.getGroupId().toBase64());
409 logger
.debug("Updating own profile key in group " + groupInfoV2
.getGroupId().toBase64());
411 final var selfRecipientId
= context
.getAccount().getSelfRecipientId();
412 final var profileKeyCredential
= context
.getProfileHelper().getExpiringProfileKeyCredential(selfRecipientId
);
413 if (profileKeyCredential
== null) {
414 logger
.trace("Cannot update profile key as self does not have a versioned profile");
418 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
419 final var change
= groupOperations
.createUpdateProfileKeyCredentialChange(profileKeyCredential
);
420 change
.setSourceUuid(getSelfAci().toByteString());
421 return commitChange(groupInfoV2
, change
);
424 GroupChange
joinGroup(
425 GroupMasterKey groupMasterKey
,
426 GroupLinkPassword groupLinkPassword
,
427 DecryptedGroupJoinInfo decryptedGroupJoinInfo
428 ) throws IOException
{
429 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupMasterKey
);
430 final var groupOperations
= dependencies
.getGroupsV2Operations().forGroup(groupSecretParams
);
432 final var selfRecipientId
= context
.getAccount().getSelfRecipientId();
433 final var profileKeyCredential
= context
.getProfileHelper().getExpiringProfileKeyCredential(selfRecipientId
);
434 if (profileKeyCredential
== null) {
435 throw new IOException("Cannot join a V2 group as self does not have a versioned profile");
438 var requestToJoin
= decryptedGroupJoinInfo
.getAddFromInviteLink() == AccessControl
.AccessRequired
.ADMINISTRATOR
;
439 var change
= requestToJoin
440 ? groupOperations
.createGroupJoinRequest(profileKeyCredential
)
441 : groupOperations
.createGroupJoinDirect(profileKeyCredential
);
443 change
.setSourceUuid(context
.getRecipientHelper()
444 .resolveSignalServiceAddress(selfRecipientId
)
448 return commitChange(groupSecretParams
, decryptedGroupJoinInfo
.getRevision(), change
, groupLinkPassword
);
451 Pair
<DecryptedGroup
, GroupChange
> acceptInvite(GroupInfoV2 groupInfoV2
) throws IOException
{
452 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
454 final var selfRecipientId
= context
.getAccount().getSelfRecipientId();
455 final var profileKeyCredential
= context
.getProfileHelper().getExpiringProfileKeyCredential(selfRecipientId
);
456 if (profileKeyCredential
== null) {
457 throw new IOException("Cannot join a V2 group as self does not have a versioned profile");
460 final var change
= groupOperations
.createAcceptInviteChange(profileKeyCredential
);
462 final var aci
= context
.getRecipientHelper().resolveSignalServiceAddress(selfRecipientId
).getServiceId();
463 change
.setSourceUuid(aci
.toByteString());
465 return commitChange(groupInfoV2
, change
);
468 Pair
<DecryptedGroup
, GroupChange
> setMemberAdmin(
469 GroupInfoV2 groupInfoV2
, RecipientId recipientId
, boolean admin
470 ) throws IOException
{
471 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
472 final var address
= context
.getRecipientHelper().resolveSignalServiceAddress(recipientId
);
473 final var newRole
= admin ? Member
.Role
.ADMINISTRATOR
: Member
.Role
.DEFAULT
;
474 final var change
= groupOperations
.createChangeMemberRole(address
.getServiceId().uuid(), newRole
);
475 return commitChange(groupInfoV2
, change
);
478 Pair
<DecryptedGroup
, GroupChange
> setMessageExpirationTimer(
479 GroupInfoV2 groupInfoV2
, int messageExpirationTimer
480 ) throws IOException
{
481 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
482 final var change
= groupOperations
.createModifyGroupTimerChange(messageExpirationTimer
);
483 return commitChange(groupInfoV2
, change
);
486 Pair
<DecryptedGroup
, GroupChange
> setIsAnnouncementGroup(
487 GroupInfoV2 groupInfoV2
, boolean isAnnouncementGroup
488 ) throws IOException
{
489 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
490 final var change
= groupOperations
.createAnnouncementGroupChange(isAnnouncementGroup
);
491 return commitChange(groupInfoV2
, change
);
494 private AccessControl
.AccessRequired
toAccessControl(final GroupLinkState state
) {
495 return switch (state
) {
496 case DISABLED
-> AccessControl
.AccessRequired
.UNSATISFIABLE
;
497 case ENABLED
-> AccessControl
.AccessRequired
.ANY
;
498 case ENABLED_WITH_APPROVAL
-> AccessControl
.AccessRequired
.ADMINISTRATOR
;
502 private AccessControl
.AccessRequired
toAccessControl(final GroupPermission permission
) {
503 return switch (permission
) {
504 case EVERY_MEMBER
-> AccessControl
.AccessRequired
.MEMBER
;
505 case ONLY_ADMINS
-> AccessControl
.AccessRequired
.ADMINISTRATOR
;
509 private GroupsV2Operations
.GroupOperations
getGroupOperations(final GroupInfoV2 groupInfoV2
) {
510 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupInfoV2
.getMasterKey());
511 return dependencies
.getGroupsV2Operations().forGroup(groupSecretParams
);
514 private Pair
<DecryptedGroup
, GroupChange
> revokeInvites(
515 GroupInfoV2 groupInfoV2
, Set
<DecryptedPendingMember
> pendingMembers
516 ) throws IOException
{
517 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
518 final var uuidCipherTexts
= pendingMembers
.stream().map(member
-> {
520 return new UuidCiphertext(member
.getUuidCipherText().toByteArray());
521 } catch (InvalidInputException e
) {
522 throw new AssertionError(e
);
524 }).collect(Collectors
.toSet());
525 return commitChange(groupInfoV2
, groupOperations
.createRemoveInvitationChange(uuidCipherTexts
));
528 private Pair
<DecryptedGroup
, GroupChange
> approveJoinRequest(
529 GroupInfoV2 groupInfoV2
, Set
<UUID
> uuids
530 ) throws IOException
{
531 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
532 return commitChange(groupInfoV2
, groupOperations
.createApproveGroupJoinRequest(uuids
));
535 private Pair
<DecryptedGroup
, GroupChange
> refuseJoinRequest(
536 GroupInfoV2 groupInfoV2
, Set
<UUID
> uuids
537 ) throws IOException
{
538 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
539 return commitChange(groupInfoV2
, groupOperations
.createRefuseGroupJoinRequest(uuids
, false, List
.of()));
542 private Pair
<DecryptedGroup
, GroupChange
> ejectMembers(
543 GroupInfoV2 groupInfoV2
, Set
<UUID
> uuids
544 ) throws IOException
{
545 final GroupsV2Operations
.GroupOperations groupOperations
= getGroupOperations(groupInfoV2
);
546 return commitChange(groupInfoV2
, groupOperations
.createRemoveMembersChange(uuids
, false, List
.of()));
549 private Pair
<DecryptedGroup
, GroupChange
> commitChange(
550 GroupInfoV2 groupInfoV2
, GroupChange
.Actions
.Builder change
551 ) throws IOException
{
552 final var groupSecretParams
= GroupSecretParams
.deriveFromMasterKey(groupInfoV2
.getMasterKey());
553 final var groupOperations
= dependencies
.getGroupsV2Operations().forGroup(groupSecretParams
);
554 final var previousGroupState
= groupInfoV2
.getGroup();
555 final var nextRevision
= previousGroupState
.getRevision() + 1;
556 final var changeActions
= change
.setRevision(nextRevision
).build();
557 final DecryptedGroupChange decryptedChange
;
558 final DecryptedGroup decryptedGroupState
;
561 decryptedChange
= groupOperations
.decryptChange(changeActions
, getSelfAci().uuid());
562 decryptedGroupState
= DecryptedGroupUtil
.apply(previousGroupState
, decryptedChange
);
563 } catch (VerificationFailedException
| InvalidGroupStateException
| NotAbleToApplyGroupV2ChangeException e
) {
564 throw new IOException(e
);
567 var signedGroupChange
= dependencies
.getGroupsV2Api()
568 .patchGroup(changeActions
, getGroupAuthForToday(groupSecretParams
), Optional
.empty());
570 return new Pair
<>(decryptedGroupState
, signedGroupChange
);
573 private GroupChange
commitChange(
574 GroupSecretParams groupSecretParams
,
576 GroupChange
.Actions
.Builder change
,
577 GroupLinkPassword password
578 ) throws IOException
{
579 final var nextRevision
= currentRevision
+ 1;
580 final var changeActions
= change
.setRevision(nextRevision
).build();
582 return dependencies
.getGroupsV2Api()
583 .patchGroup(changeActions
,
584 getGroupAuthForToday(groupSecretParams
),
585 Optional
.ofNullable(password
).map(GroupLinkPassword
::serialize
));
588 Pair
<ServiceId
, ProfileKey
> getAuthoritativeProfileKeyFromChange(final DecryptedGroupChange change
) {
589 UUID editor
= UuidUtil
.fromByteStringOrNull(change
.getEditor());
590 final var editorProfileKeyBytes
= Stream
.concat(Stream
.of(change
.getNewMembersList().stream(),
591 change
.getPromotePendingMembersList().stream(),
592 change
.getModifiedProfileKeysList().stream())
593 .flatMap(Function
.identity())
594 .filter(m
-> UuidUtil
.fromByteString(m
.getUuid()).equals(editor
))
595 .map(DecryptedMember
::getProfileKey
),
596 change
.getNewRequestingMembersList()
598 .filter(m
-> UuidUtil
.fromByteString(m
.getUuid()).equals(editor
))
599 .map(DecryptedRequestingMember
::getProfileKey
)).findFirst();
601 if (editorProfileKeyBytes
.isEmpty()) {
605 ProfileKey profileKey
;
607 profileKey
= new ProfileKey(editorProfileKeyBytes
.get().toByteArray());
608 } catch (InvalidInputException e
) {
609 logger
.debug("Bad profile key in group");
613 return new Pair
<>(ServiceId
.from(editor
), profileKey
);
616 DecryptedGroup
getUpdatedDecryptedGroup(DecryptedGroup group
, DecryptedGroupChange decryptedGroupChange
) {
618 return DecryptedGroupUtil
.apply(group
, decryptedGroupChange
);
619 } catch (NotAbleToApplyGroupV2ChangeException e
) {
624 DecryptedGroupChange
getDecryptedGroupChange(byte[] signedGroupChange
, GroupMasterKey groupMasterKey
) {
625 if (signedGroupChange
!= null) {
626 var groupOperations
= dependencies
.getGroupsV2Operations()
627 .forGroup(GroupSecretParams
.deriveFromMasterKey(groupMasterKey
));
630 return groupOperations
.decryptChange(GroupChange
.parseFrom(signedGroupChange
), true).orElse(null);
631 } catch (VerificationFailedException
| InvalidGroupStateException
| InvalidProtocolBufferException e
) {
639 private static long currentDaySeconds() {
640 return TimeUnit
.DAYS
.toSeconds(TimeUnit
.MILLISECONDS
.toDays(System
.currentTimeMillis()));
643 private GroupsV2AuthorizationString
getGroupAuthForToday(
644 final GroupSecretParams groupSecretParams
645 ) throws IOException
{
646 final var todaySeconds
= currentDaySeconds();
647 if (groupApiCredentials
== null || !groupApiCredentials
.containsKey(todaySeconds
)) {
648 // Returns credentials for the next 7 days
649 groupApiCredentials
= dependencies
.getGroupsV2Api().getCredentials(todaySeconds
);
650 // TODO cache credentials on disk until they expire
653 return getAuthorizationString(groupSecretParams
, todaySeconds
);
654 } catch (VerificationFailedException e
) {
655 logger
.debug("Group api credentials invalid, renewing and trying again.");
656 groupApiCredentials
.clear();
659 groupApiCredentials
= dependencies
.getGroupsV2Api().getCredentials(todaySeconds
);
661 return getAuthorizationString(groupSecretParams
, todaySeconds
);
662 } catch (VerificationFailedException e
) {
663 throw new IOException(e
);
667 private GroupsV2AuthorizationString
getAuthorizationString(
668 final GroupSecretParams groupSecretParams
, final long todaySeconds
669 ) throws VerificationFailedException
{
670 var authCredentialResponse
= groupApiCredentials
.get(todaySeconds
);
671 final var aci
= getSelfAci();
672 final var pni
= getSelfPni();
673 return dependencies
.getGroupsV2Api()
674 .getGroupsV2AuthorizationString(aci
, pni
, todaySeconds
, groupSecretParams
, authCredentialResponse
);
677 private ACI
getSelfAci() {
678 return context
.getAccount().getAci();
681 private PNI
getSelfPni() {
682 return context
.getAccount().getPni();