]> nmode's Git Repositories - signal-cli/blob - lib/src/main/java/org/asamk/signal/manager/helper/GroupV2Helper.java
Update dependencies
[signal-cli] / lib / src / main / java / org / asamk / signal / manager / helper / GroupV2Helper.java
1 package org.asamk.signal.manager.helper;
2
3 import com.google.protobuf.ByteString;
4 import com.google.protobuf.InvalidProtocolBufferException;
5
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;
48
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;
55 import java.util.Set;
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;
61
62 class GroupV2Helper {
63
64 private final static Logger logger = LoggerFactory.getLogger(GroupV2Helper.class);
65
66 private final SignalDependencies dependencies;
67 private final Context context;
68
69 private HashMap<Long, AuthCredentialWithPniResponse> groupApiCredentials;
70
71 GroupV2Helper(final Context context) {
72 this.dependencies = context.getDependencies();
73 this.context = context;
74 }
75
76 void clearAuthCredentialCache() {
77 groupApiCredentials = null;
78 }
79
80 DecryptedGroup getDecryptedGroup(final GroupSecretParams groupSecretParams) throws NotAGroupMemberException {
81 try {
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);
87 }
88 logger.warn("Failed to retrieve Group V2 info, ignoring: {}", e.getMessage());
89 return null;
90 } catch (IOException | VerificationFailedException | InvalidGroupStateException e) {
91 logger.warn("Failed to retrieve Group V2 info, ignoring: {}", e.getMessage());
92 return null;
93 }
94 }
95
96 DecryptedGroupJoinInfo getDecryptedGroupJoinInfo(
97 GroupMasterKey groupMasterKey, GroupLinkPassword password
98 ) throws IOException, GroupLinkNotActiveException {
99 var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupMasterKey);
100
101 return dependencies.getGroupsV2Api()
102 .getGroupJoinInfo(groupSecretParams,
103 Optional.ofNullable(password).map(GroupLinkPassword::serialize),
104 getGroupAuthForToday(groupSecretParams));
105 }
106
107 GroupHistoryPage getDecryptedGroupHistoryPage(
108 final GroupSecretParams groupSecretParams, int fromRevision
109 ) throws NotAGroupMemberException {
110 try {
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);
117 }
118 logger.warn("Failed to retrieve Group V2 history, ignoring: {}", e.getMessage());
119 return null;
120 } catch (IOException | VerificationFailedException | InvalidGroupStateException e) {
121 logger.warn("Failed to retrieve Group V2 history, ignoring: {}", e.getMessage());
122 return null;
123 }
124 }
125
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();
131 }
132 }
133 return partialDecryptedGroup.getRevision();
134 }
135
136 Pair<GroupInfoV2, DecryptedGroup> createGroup(
137 String name, Set<RecipientId> members, byte[] avatarFile
138 ) {
139 final var newGroup = buildNewGroup(name, members, avatarFile);
140 if (newGroup == null) {
141 return null;
142 }
143
144 final var groupSecretParams = newGroup.getGroupSecretParams();
145
146 final GroupsV2AuthorizationString groupAuthForToday;
147 final DecryptedGroup decryptedGroup;
148 try {
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());
154 return null;
155 }
156 if (decryptedGroup == null) {
157 logger.warn("Failed to create V2 group, unknown error!");
158 return null;
159 }
160
161 final var groupId = GroupUtils.getGroupIdV2(groupSecretParams);
162 final var masterKey = groupSecretParams.getMasterKey();
163 var g = new GroupInfoV2(groupId, masterKey, context.getAccount().getRecipientResolver());
164
165 return new Pair<>(g, decryptedGroup);
166 }
167
168 private GroupsV2Operations.NewGroup buildNewGroup(
169 String name, Set<RecipientId> members, byte[] avatar
170 ) {
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");
175 return null;
176 }
177
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,
184 credentials,
185 (uuid, credential) -> new GroupCandidate(uuid, Optional.ofNullable(credential)))
186 .collect(Collectors.toSet());
187
188 final var groupSecretParams = GroupSecretParams.generate();
189 return dependencies.getGroupsV2Operations()
190 .createNewGroup(groupSecretParams,
191 name,
192 Optional.ofNullable(avatar),
193 self,
194 candidates,
195 Member.Role.DEFAULT,
196 0);
197 }
198
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);
204
205 var change = name != null ? groupOperations.createModifyGroupTitle(name) : GroupChange.Actions.newBuilder();
206
207 if (description != null) {
208 change.setModifyDescription(groupOperations.createModifyGroupDescriptionAction(description));
209 }
210
211 if (avatarFile != null) {
212 var avatarCdnKey = dependencies.getGroupsV2Api()
213 .uploadAvatar(avatarFile, groupSecretParams, getGroupAuthForToday(groupSecretParams));
214 change.setModifyAvatar(GroupChange.Actions.ModifyAvatarAction.newBuilder().setAvatar(avatarCdnKey));
215 }
216
217 change.setSourceUuid(getSelfAci().toByteString());
218
219 return commitChange(groupInfoV2, change);
220 }
221
222 Pair<DecryptedGroup, GroupChange> addMembers(
223 GroupInfoV2 groupInfoV2, Set<RecipientId> newMembers
224 ) throws IOException {
225 GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
226
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,
232 credentials,
233 (uuid, credential) -> new GroupCandidate(uuid, Optional.ofNullable(credential)))
234 .collect(Collectors.toSet());
235 final var bannedUuids = groupInfoV2.getBannedMembers()
236 .stream()
237 .map(member -> context.getRecipientHelper().resolveSignalServiceAddress(member).getServiceId().uuid())
238 .collect(Collectors.toSet());
239
240 final var aci = getSelfAci();
241 final var change = groupOperations.createModifyGroupMembershipChange(candidates, bannedUuids, aci.uuid());
242
243 change.setSourceUuid(getSelfAci().toByteString());
244
245 return commitChange(groupInfoV2, change);
246 }
247
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());
254
255 if (selfPendingMember.isPresent()) {
256 return revokeInvites(groupInfoV2, Set.of(selfPendingMember.get()));
257 }
258
259 final var adminUuids = membersToMakeAdmin.stream()
260 .map(context.getRecipientHelper()::resolveSignalServiceAddress)
261 .map(SignalServiceAddress::getServiceId)
262 .map(ServiceId::uuid)
263 .toList();
264 final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
265 return commitChange(groupInfoV2,
266 groupOperations.createLeaveAndPromoteMembersToAdmin(selfAci.uuid(), adminUuids));
267 }
268
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);
278 }
279
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);
289 }
290
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);
300 }
301
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)
312 .map(Optional::get)
313 .collect(Collectors.toSet());
314 return revokeInvites(groupInfoV2, memberUuids);
315 }
316
317 Pair<DecryptedGroup, GroupChange> banMembers(
318 GroupInfoV2 groupInfoV2, Set<RecipientId> block
319 ) throws IOException {
320 GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
321
322 final var uuids = block.stream()
323 .map(member -> context.getRecipientHelper().resolveSignalServiceAddress(member).getServiceId().uuid())
324 .collect(Collectors.toSet());
325
326 final var change = groupOperations.createBanUuidsChange(uuids,
327 false,
328 groupInfoV2.getGroup().getBannedMembersList());
329
330 change.setSourceUuid(getSelfAci().toByteString());
331
332 return commitChange(groupInfoV2, change);
333 }
334
335 Pair<DecryptedGroup, GroupChange> unbanMembers(
336 GroupInfoV2 groupInfoV2, Set<RecipientId> block
337 ) throws IOException {
338 GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
339
340 final var uuids = block.stream()
341 .map(member -> context.getRecipientHelper().resolveSignalServiceAddress(member).getServiceId().uuid())
342 .collect(Collectors.toSet());
343
344 final var change = groupOperations.createUnbanUuidsChange(uuids);
345
346 change.setSourceUuid(getSelfAci().toByteString());
347
348 return commitChange(groupInfoV2, change);
349 }
350
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);
356 }
357
358 Pair<DecryptedGroup, GroupChange> setGroupLinkState(
359 GroupInfoV2 groupInfoV2, GroupLinkState state
360 ) throws IOException {
361 final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
362
363 final var accessRequired = toAccessControl(state);
364 final var requiresNewPassword = state != GroupLinkState.DISABLED && groupInfoV2.getGroup()
365 .getInviteLinkPassword()
366 .isEmpty();
367
368 final var change = requiresNewPassword ? groupOperations.createModifyGroupLinkPasswordAndRightsChange(
369 GroupLinkPassword.createNew().serialize(),
370 accessRequired) : groupOperations.createChangeJoinByLinkRights(accessRequired);
371 return commitChange(groupInfoV2, change);
372 }
373
374 Pair<DecryptedGroup, GroupChange> setEditDetailsPermission(
375 GroupInfoV2 groupInfoV2, GroupPermission permission
376 ) throws IOException {
377 final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
378
379 final var accessRequired = toAccessControl(permission);
380 final var change = groupOperations.createChangeAttributesRights(accessRequired);
381 return commitChange(groupInfoV2, change);
382 }
383
384 Pair<DecryptedGroup, GroupChange> setAddMemberPermission(
385 GroupInfoV2 groupInfoV2, GroupPermission permission
386 ) throws IOException {
387 final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
388
389 final var accessRequired = toAccessControl(permission);
390 final var change = groupOperations.createChangeMembershipRights(accessRequired);
391 return commitChange(groupInfoV2, change);
392 }
393
394 Pair<DecryptedGroup, GroupChange> updateSelfProfileKey(GroupInfoV2 groupInfoV2) throws IOException {
395 Optional<DecryptedMember> selfInGroup = groupInfoV2.getGroup() == null
396 ? Optional.empty()
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());
400 return null;
401 }
402
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());
407 return null;
408 }
409 logger.debug("Updating own profile key in group " + groupInfoV2.getGroupId().toBase64());
410
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");
415 return null;
416 }
417
418 final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
419 final var change = groupOperations.createUpdateProfileKeyCredentialChange(profileKeyCredential);
420 change.setSourceUuid(getSelfAci().toByteString());
421 return commitChange(groupInfoV2, change);
422 }
423
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);
431
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");
436 }
437
438 var requestToJoin = decryptedGroupJoinInfo.getAddFromInviteLink() == AccessControl.AccessRequired.ADMINISTRATOR;
439 var change = requestToJoin
440 ? groupOperations.createGroupJoinRequest(profileKeyCredential)
441 : groupOperations.createGroupJoinDirect(profileKeyCredential);
442
443 change.setSourceUuid(context.getRecipientHelper()
444 .resolveSignalServiceAddress(selfRecipientId)
445 .getServiceId()
446 .toByteString());
447
448 return commitChange(groupSecretParams, decryptedGroupJoinInfo.getRevision(), change, groupLinkPassword);
449 }
450
451 Pair<DecryptedGroup, GroupChange> acceptInvite(GroupInfoV2 groupInfoV2) throws IOException {
452 final GroupsV2Operations.GroupOperations groupOperations = getGroupOperations(groupInfoV2);
453
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");
458 }
459
460 final var change = groupOperations.createAcceptInviteChange(profileKeyCredential);
461
462 final var aci = context.getRecipientHelper().resolveSignalServiceAddress(selfRecipientId).getServiceId();
463 change.setSourceUuid(aci.toByteString());
464
465 return commitChange(groupInfoV2, change);
466 }
467
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);
476 }
477
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);
484 }
485
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);
492 }
493
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;
499 };
500 }
501
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;
506 };
507 }
508
509 private GroupsV2Operations.GroupOperations getGroupOperations(final GroupInfoV2 groupInfoV2) {
510 final var groupSecretParams = GroupSecretParams.deriveFromMasterKey(groupInfoV2.getMasterKey());
511 return dependencies.getGroupsV2Operations().forGroup(groupSecretParams);
512 }
513
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 -> {
519 try {
520 return new UuidCiphertext(member.getUuidCipherText().toByteArray());
521 } catch (InvalidInputException e) {
522 throw new AssertionError(e);
523 }
524 }).collect(Collectors.toSet());
525 return commitChange(groupInfoV2, groupOperations.createRemoveInvitationChange(uuidCipherTexts));
526 }
527
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));
533 }
534
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()));
540 }
541
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()));
547 }
548
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;
559
560 try {
561 decryptedChange = groupOperations.decryptChange(changeActions, getSelfAci().uuid());
562 decryptedGroupState = DecryptedGroupUtil.apply(previousGroupState, decryptedChange);
563 } catch (VerificationFailedException | InvalidGroupStateException | NotAbleToApplyGroupV2ChangeException e) {
564 throw new IOException(e);
565 }
566
567 var signedGroupChange = dependencies.getGroupsV2Api()
568 .patchGroup(changeActions, getGroupAuthForToday(groupSecretParams), Optional.empty());
569
570 return new Pair<>(decryptedGroupState, signedGroupChange);
571 }
572
573 private GroupChange commitChange(
574 GroupSecretParams groupSecretParams,
575 int currentRevision,
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();
581
582 return dependencies.getGroupsV2Api()
583 .patchGroup(changeActions,
584 getGroupAuthForToday(groupSecretParams),
585 Optional.ofNullable(password).map(GroupLinkPassword::serialize));
586 }
587
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()
597 .stream()
598 .filter(m -> UuidUtil.fromByteString(m.getUuid()).equals(editor))
599 .map(DecryptedRequestingMember::getProfileKey)).findFirst();
600
601 if (editorProfileKeyBytes.isEmpty()) {
602 return null;
603 }
604
605 ProfileKey profileKey;
606 try {
607 profileKey = new ProfileKey(editorProfileKeyBytes.get().toByteArray());
608 } catch (InvalidInputException e) {
609 logger.debug("Bad profile key in group");
610 return null;
611 }
612
613 return new Pair<>(ServiceId.from(editor), profileKey);
614 }
615
616 DecryptedGroup getUpdatedDecryptedGroup(DecryptedGroup group, DecryptedGroupChange decryptedGroupChange) {
617 try {
618 return DecryptedGroupUtil.apply(group, decryptedGroupChange);
619 } catch (NotAbleToApplyGroupV2ChangeException e) {
620 return null;
621 }
622 }
623
624 DecryptedGroupChange getDecryptedGroupChange(byte[] signedGroupChange, GroupMasterKey groupMasterKey) {
625 if (signedGroupChange != null) {
626 var groupOperations = dependencies.getGroupsV2Operations()
627 .forGroup(GroupSecretParams.deriveFromMasterKey(groupMasterKey));
628
629 try {
630 return groupOperations.decryptChange(GroupChange.parseFrom(signedGroupChange), true).orElse(null);
631 } catch (VerificationFailedException | InvalidGroupStateException | InvalidProtocolBufferException e) {
632 return null;
633 }
634 }
635
636 return null;
637 }
638
639 private static long currentDaySeconds() {
640 return TimeUnit.DAYS.toSeconds(TimeUnit.MILLISECONDS.toDays(System.currentTimeMillis()));
641 }
642
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
651 }
652 try {
653 return getAuthorizationString(groupSecretParams, todaySeconds);
654 } catch (VerificationFailedException e) {
655 logger.debug("Group api credentials invalid, renewing and trying again.");
656 groupApiCredentials.clear();
657 }
658
659 groupApiCredentials = dependencies.getGroupsV2Api().getCredentials(todaySeconds);
660 try {
661 return getAuthorizationString(groupSecretParams, todaySeconds);
662 } catch (VerificationFailedException e) {
663 throw new IOException(e);
664 }
665 }
666
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);
675 }
676
677 private ACI getSelfAci() {
678 return context.getAccount().getAci();
679 }
680
681 private PNI getSelfPni() {
682 return context.getAccount().getPni();
683 }
684 }